Answer the question
In order to leave comments, you need to log in
Do I need to remove listeners for UnityEvent?
Good afternoon. If I do Destroy(/DestroyImmediate) on a GameObject, do I have to unsubscribe all listeners in MonoBehavoiur's from UnityEvent instances? Or does the engine (Unity) itself remove subscribers and the object is immediately marked for the garbage collector? Cache behavior is not considered.
Answer the question
In order to leave comments, you need to log in
If the event source has been removed, then why do anything with the subscribers? Subscribers will only be removed if the event source is their parent in the hierarchy. If subscribers do not store a reference to the object, then nothing needs to be done. On the other hand, if you deleted the subscriber without unsubscribing, then yes, the event source will have a reference to the killed object, and then there will be a memory leak. In this case, the subscriber must unsubscribe before dying, but the UnityEvent is implemented in such a way that it does not cause dead subscriptions, so decide for yourself, if the lifetime of objects varies greatly, then unsubscribe.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question