G
G
GFX Data2018-02-02 19:55:44
C++ / C#
GFX Data, 2018-02-02 19:55:44

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

1 answer(s)
D
Daniil Basmanov, 2018-02-02
@ShockWave2048

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 question

Ask a Question

731 491 924 answers to any question