Bastrix
Bastrix

Reputation: 159

Why is C# is not removing listeners from an Action delegate?

So I've built a very basic event manager for a game in Unity and I'm saving references of Actions in a dictionary like this:

public void SubscribeToAction(string actionKey, Action<object> listener)
{
    Action<object> action;
    if(actionList.TryGetValue(actionKey, out action)){
        action += listener;
    }else{
        action += listener;
        actionList.Add(actionKey, action);
    }
}

But what happens is that even though I unsubscribe when I exit the scene, I find that calls are being made to old listeners and I'm getting a null exception:

public void UnSubscribe(string actionKey, Action<object> listener)
{
    Action<object> action;
    if(actionList.TryGetValue(actionKey, out action)){
        action -= listener;
    }
}

The only solution I've found is to clear the entire dictionary when exit the scene and adding the subscriptions again on start() methods.

Upvotes: 0

Views: 338

Answers (1)

Servy
Servy

Reputation: 203804

action += listener; and action -= listener; are just changing the local variable action. They're not changing the value in the dictionary. If you want to change the value in the dictionary you'll need to set the value in that dictionary, in your case, to the value of action.

Upvotes: 3

Related Questions