I have an issue, of which I’m unsure if it is an actual problem:
My EventManager class stores UnityEvents in a collection and manages, adding and removing listeners as well as raising events. It also follows a Singleton Pattern with a static instance and persists between scenes.
Every listener class calls EventManager.AddListener(…) in OnEnable() and EventManager.RemoveListener(…) in OnDisable(), because I’m assuming I must clean listener references when the application quits so to not create a memory leak. (Please correct me, if this assumption is wrong!)
For probably a random reason, my EventManager is destroyed when quitting Play Mode before all other objects and therefore the listeners won’t be removed. I can easily handle exceptions with a null check, but then I’m afraid that my references are leaking into the scene. I’m unsure what this means for my final build on the device, too.
Should this even trouble me or are any list references destroyed on application quit anyway? Is there a way of changing the execution order so that OnDestroy is called later for my EventManager?
Thank you!
It should not trouble you, no. There will be no leaking from this.
For future reference, OnDisable is a good spot to handle unregistering and it is indeed invoked before OnDestroy. Do not rely on specific execution order of instances. Down that path you’ll only find pain and misery.
Also note that you do not even need to unregister with UnityEvents in response to dynamic runtime destruction. That is one of the nicer things setting UnityEvents apart from .net events and delegates.
Thanks! I’ve double checked what was going on and it seems that my instances were only destroyed before unsubscribing listeners when I stopped Play Mode in the editor, but not when actually loading scenes or in my build.
I disagree with you. Execution order maybe a good tool.
I use my Execution Order Configurator which can set up order by namespace, base class or interface. It is much more convenient than your “Project Settings > Script Execution Order”.
But there is one big promlem. Execution Order does not affect on order of OnDestroy at all.
Zenject can set up execution order for their POCO scripts and order for Dispose is reversed. So, object which was created first, will be destroyed last. This would be convenient for manager scripts.
I hope you pay attention to this.