Reputation: 11
I try to write event bus. I have
public class EventBusArgs<T> : EventArgs
{
private T _value;
public EventBusArgs(T @value)
{
_value = @value;
}
public T Value
{
get
{
return _value;
}
}
}
public enum EventType
{
None,
PrintInt1,
PrintString1,
}
public class EventManager : GlobalSingleton<EventManager>
{
private static Dictionary<EventType, EventHandler<EventArgs>> _eventBus;
public override void Awake()
{
base.Awake();
if (_eventBus == null)
{
_eventBus = new Dictionary<EventType, EventHandler<EventArgs>>();
}
}
public static void StartListening(EventType eventType, EventHandler<EventArgs> eventHandler)
{
if (_eventBus.ContainsKey(eventType))
{
_eventBus[eventType] += eventHandler;
}
else
{
_eventBus.Add(eventType, eventHandler);
}
}
public void Start()
{
StartListening(EventType.PrintInt1, PrintInt1);// error here
}
private void PrintInt1(object sender, EventBusArgs<int> number)// because it is not (object sender, EventArgs number)
{
Debug.Log($"the number in PrintInt1 is {number.Value}");
}
}
But I have error: cannot convert from "method group" to EventHandler . When I use EventArgs instead of EventBusArgs programs works without error.
How I can fix it and use EventBusArgs? Because I want use double, Vector3 and my custom classes...
Upvotes: 1
Views: 996
Reputation: 1386
Just cast the EventArgs to your EventBusArgs in the Callbacks (in this case PrintInt1).
private void PrintInt1(object sender, EventArgs eventArgs)
{
EventBusArgs<int> number = (EventBusArgs<int>)eventArgs;
Debug.Log($"the number in PrintInt1 is {number.Value}");
}
Changes can be found here: https://dotnetfiddle.net/NLsHms
Upvotes: 1