Memory leak unsubscribing using anonymous delegate

If you subscribe like this player.Health.OnDie += health => HandlePlayerDie(player); then you cannot unsubscribe using player.Health.OnDie -= health => HandlePlayerDie(player);, because it is a reference to a new anonymous delegate.

It can be validated with the following experiment:

       public event Action Test;

        private void Start()
            Test += () => OnTest();
            Test -= () => OnTest();
        private void OnTest()
            Debug.LogWarning("DID NOT UNSUBSCRIBE");

Better approach would be resolving tank player from Health object inside a method.

Privacy & Terms