I have declared an event and I can add delegates to it. However, I would like to have a dictionary of supported events, so that derived classes can state which events they implement and which they do not.
When I don't use the dictionary, my code works fine, I can add listeners in other classes and invoke the event in derived classes by calling OnPickup
:
public delegate void EventDelegate();
protected static event EventDelegate pickupEvent;
public void AddListener(EventName name, EventDelegate listener)
{
pickupEvent += listener;
}
protected virtual void OnPickup()
{
if (pickupEvent != null)
{
pickupEvent();
}
}
But when I use the dictionary when adding the delegate, it doesn't work. pickupEvent
is null when I call it in OnPickup()
:
public delegate void EventDelegate();
protected static event EventDelegate pickupEvent;
//dictionary of events supported by this class
protected Dictionary<EventName, EventDelegate> events = new Dictionary<EventName, EventDelegate>();
public void AddListener(EventName name, EventDelegate listener)
{
events.Add(name, pickupEvent);
if (events.ContainsKey(name))
{
//we support this event type, add the delegate
print("adding a listener");
events[name] += listener;
}
}
protected virtual void OnPickup()
{
if (pickupEvent != null)
{
pickupEvent();
}
}
It's not clear to me why this doesn't work - is this something about events and delegates that I'm missing?