I have the following dictionary:
private Dictionary<string, Action<GameObject, int, int, int, int>> eventDictionary;
I wish to keep a dictionary of Actions (basically delegates) so that whenever I wish to subscribe to an event name, I can subscribe to the same event for all my subscribers.
This is my function to listen to a certain event string:
public static void StartListening(string eventName, Action<GameObject, int, int, int, int> listener)
{
Action<GameObject, int, int, int, int> thisEvent = null;
if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
{
thisEvent += listener;
// the code reaches this
}
else
{
thisEvent += listener;
instance.eventDictionary.Add(eventName, thisEvent);
}
}
Now I try
EventManager.StartListening("Move", Moved);
EventManager.StartListening("Move", Moved);
EventManager.StartListening("Move", Moved);
EventManager.StartListening("Move", Moved);
// Log here to get how many subscribers there are to the event "Move"
// Result: only 1 listener
Only the first added listener will actually register, the rest "disappear" after adding them. I debugged this error for nearly 4 hours, before finally testing to see if maybe the line thisEvent += listener;
was malfunctioning. When I added a remove and subsequent add back to the dictionary,
public static void StartListening(string eventName, Action<GameObject, int, int, int, int> listener)
{
Action<GameObject, int, int, int, int> thisEvent = null;
if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
{
thisEvent += listener;
instance.eventDictionary.Remove(eventName);
instance.eventDictionary.Add(eventName, thisEvent);
}
else
{
thisEvent += listener;
instance.eventDictionary.Add(eventName, thisEvent);
}
}
the delegates finally got added as expected.
EventManager.StartListening("Move", Moved);
EventManager.StartListening("Move", Moved);
EventManager.StartListening("Move", Moved);
EventManager.StartListening("Move", Moved);
// Log here to get how many subscribers there are to the event "Move"
// Result: 4 listeners
This is one of the most nonsensical errors I have ever gotten. Aren't all values in a dictionary that aren't strings, ints, etc. supposed to be retrieved by reference, not by value? Why do I get a clone of the Action here, rather than a reference?
PS: GameObject is a Unity class. This is my Moved function:
public void Moved(GameObject invoker, int x, int z, int tx, int tz)
{
//Some code here
}