- Home /
Order of destroy objects and OnDestroy event
Hi.
I'm working on a game where some singletons are present between scenes. However, other singletons are different in each scene so I don't use DontDestroyOnLoad method for these.
The problem I found is that the game object that contains the singleton is destroyed in an arbitrary order (checked by debug logs in the console). I can change the script execution order in the project settings but this seems not to work with OnDestroy and OnDisable events.
The only thing I need is my singleton to be destroyed the last one. Is there a way to control the order of destroyed objects when a scene is loaded?
Thanks in advance!
I also can't seem to find a way to control destruction order. In my tests, "Script Execution Order" doesn't seem to apply to OnDisable and OnDestroy events. This is also consistent with the documentation which only mentions Awake, OnEnable, and Update.
So as far as I can tell, there is no way to control this. I would love to be proven wrong here though
Oddly enough one of the things that seem to deter$$anonymous$$e the order in onDestroy and onDisable is the size of the string ("OnDestroy last" has 13 letters and "OnDestroy first" has 14). maybe its the size that deter$$anonymous$$es execution?
It was a coincidence that happened 6 times in a row, btw please stop necroposting.
Agree to disagree then. Even if you don't have an answer, it can still help to provide more information on the problem. And it seems pointless to just make duplicate questions like you suggest, when you can just add more information to an existing one. This is how stack overflow works and for good reason I think
Then you need to use comments, not answers. Answers are for answering the question only.
Answer by ShawnFeatherly · Jul 07, 2017 at 03:55 AM
Discovered the same issue. It's a bummer OnDestroy doesn't respect script execution order.
Couldn't find a way to set the order. Instead, discovered a way to deal with not knowing the order. I ended up creating a public static bool
called WasDestroyed
inside of the singleton class to track OnDestroy. WasDestroyed
's value is set when the singleton calls its OnDestroy. Then I could check WasDestroyed
in other scripts OnDestroy to see if I should be accessing the instance or not.
Answer by Dizy · Feb 14, 2018 at 11:01 AM
I encountered the same problem and if someone came across this topic I recommend to use a scene and to put your singletons inside, a scene manager.
Using SceneManager.LoadScene(, LoadSceneMode.Additive) and SceneManager.UnloadScene
Reference : Multi-Scene editing
Your answer
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
execution order of Destroy and Physisc.Raycast 1 Answer
Unregister Singleton Events before OnDestroy is called 1 Answer
Using Singleton but getting a null reference 2 Answers
Trouble with DestroyOnLoad,Game won't start after player dies once 1 Answer