- Home /
Unregister Singleton Events before OnDestroy is called
Hi All,
I'm trying to unregister some event listeners when my object is been destroyed. The events are part of a singleton (using lazy initialisation), so when I want to unregister I just do something like:
Singleton.Instance.EventToUnregister -= EventHandler;
The problem is when I quit the application, the singleton is getting destroyed before my object. So when my object attempts to unregister the listeners, it creates a singleton object (as it has already been destroyed).I have only encountered this issue while quitting the game, but it'll likely happen when switching scenes.
I know singletons and MonoBehaviour don't go well together, but is there a way around this issue?
Answer by $$anonymous$$ · Jul 21, 2014 at 09:04 PM
I think you can leave it without unsubscribing.The UnityEngine should do that internally when clearing its internal listener structure.
I know I don't need to unsubscribe if the publisher is been destroyed, but I do believe I need to unsubscribe if the object listener is been destroyed but not the publisher. I guess I need to deter$$anonymous$$e if the singleton is alive before attempting to unsubscribe, which means that lazy singleton implementation is not the approach to use here.
Wait, in that case, all you have to do is this
if (Singleton.Instance)
Singleton.Instance.EventToUnregister -= EventHandler;
Your answer
Follow this Question
Related Questions
Singleton class or delegate? 1 Answer
Order of destroy objects and OnDestroy event 2 Answers
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
OnDisable calls singleton instance, creates unwanted object + errors 1 Answer
Help to understand events and delegates (Game Manager) 2 Answers