- Home /
Why UI event handlers dont get memory leaks if listener not removed
I've seen common practice that users usually just AddListener, but never remove if listening gameObject is being destroyed.
myButton.onClick.AddListener(()=>MyFunk()); }
Is this handled behind the scenes, or Listener removal should be a must in Unity too? Personally i always remove it, im just really wondering.
OnDestroy()
myButton.onClick.RemoveListener()...
}
Answer by fafase · Sep 24, 2015 at 08:54 AM
I could be misunderstanding the wording of the docs but AddListener is meant to add a non.persistent listener.
But, the following shows a weird behaviour (at least until I get it explained):
private float myFloat = 10f;
[SerializeField] private Button button = null;
void Start( )
{
button.onClick.AddListener(MyMethod);
DestroyImmediate(this.gameObject);
}
public void MyMethod()
{
Debug.Log("Call " + this.myFloat);
this.myFloat ++;
}
the best part being that the object is surely gone, the this.myFloat still gets printed AND increased, and I don't have any persistent listener.
If I remove in Destroy then all goes fine. It seems the AddListener is creating a link to the object in memory and even triggering the GC will not collect the object. Using a weak reference would probably bring it back to life I am thinking.
What is even better is that if I create a reference to my script above and call for the myFloat value, I get it??!! Despite the inspector showing Missing(Type)??!!...
This tells me that we have here a memory leak if the programmer is not removing the listener manually, until I am proven wrong. obviously.
That's what i was thinking, Unity UI docs and people who create tutorials are not clearly pushing this in correct bounds. I've seen several commercial games code where this is standard behavior.
Your answer
Follow this Question
Related Questions
Button.OnClic.AddListener(delegate{method(object);}), wrong object sent 1 Answer
How to add OnClick listener in script to see it in inspector? 1 Answer
How would I detect a right click with an event trigger? 3 Answers
Chain UI animations with Events? 1 Answer
[4.6 - UI] How to call an event with button when the pointer is up the button image. 1 Answer