Warning: Lambda Functions on onClick.AddListener

If you decide to move your onClick.AddListeners to OnEnable() or OnDisable() and use the same lambda functions Sam had, Unity may add multiple listeners. I think this is because OnEnable may be called multiple times and because each lambda function is treated as distinct.

/// Warning this might add multiple listeners even if you clean up
// with OnDisable and RemoveAllListeners
        private void OnEnable() {
            minusButton.onClick.AddListener(() => Allocate(-1));
            plusButton.onClick.AddListener(() => Allocate(+1));
        }

The solution for me was to create IncrementByOne and DecrementByOne methods and then use those in OnEnable and OnDisable. With a specific method now, Unity will recognize not to add it multiple times even in OnEnable is called multiple times.

Yes. It is (almost) never a good idea to use lambdas as event handlers because there is no way to unsubscribe it again. I say (almost) but can’t think of any time that it is a good idea

1 Like

Privacy & Terms