.AddListener vs Editor

Are there any downsides of using

UIButton.onClick.AddListener(() => ButtonsClicks(5));

vs doing it in Editor (like dragging, selecting your callback function etc…)?
Also I noticed folks often advice removing listeners - I’m not destroying my buttons, but I hide them (.SetActive(false)).
Do I still have to remove listeners when I hide my buttons?

defining the Handler via the Editor is a Static binding
while using AddListener via code is a dynamic binding

they each have their own benefits.

Static binding uses serialized data and its quick to set up and iterate over.
dynamic binding however can access objects that are created/available at runtime.

the only benefits Static binding has over dynamic binding is a faster, iterative workflow due to a UI access. Dynamic binding can do more though due to having less limitations, but they typically take a little extra work to set up.

As for removing listeners its just good practice. if the Handlers and the callers are always getting disposed around the same time it doesn’t matter as much, but thats a very bad habit to get used to. If a Handler gets disposed without removing itself from the caller (and the caller doesn’t get disposed) then technically you have a memory leak and will get MissingReferenceExceptions when you try to invoke the caller. It doesn’t hurt to always remove them anyway.

this is why the common advice is to add the listeners in OnEnable and then remove them in OnDisable this way they will always work when needed and will automatically clean themselves up when not needed.

Make it a personal rule: Always cleanup your AddListeners. Making exceptions to this rule is either lazy or a hint at poor design.

4 Likes