- Home /
Using Toolbox Singleton Script and Reloading Scene
I was trying to use the script here - http://wiki.unity3d.com/index.php/Toolbox. I attached it to a GameObject and was putting my global vars. It works well. But if I reload the scene, I get a warning "[Singleton] Instance 'Toolbox' already destroyed on application quit. Won't create again - returning null." And I can't access my global vars again. So how do I use this script and different scenes together ?
Answer by JASlaughter · Mar 09, 2014 at 05:15 PM
Add a method to the Singleton class:
public void Reload()
{
applicationIsQuitting = false;
}
Then call it from Toolbox.Awake() using this.Reload();
Sorry, but that makes not much sense. applicationIsQuitting has been implemented to prevent recreation of the instance at edit time when using ExecuteInEdit$$anonymous$$ode. Setting it to false in Awake would render the whole point of this variable useless.
As i said in my answer the singleton implementation is missing a call to DontDestroyOnLoad in the case when the instance already exists in the scene.
Answer by Bunny83 · Jan 24, 2014 at 08:17 PM
Well, the singleton implementation which is used by the toolbox is missing a DontDestroyOnLoad in the "else" branch. The else branch is the case when you already have an instance in the scene. Since DontDestroyOnLoad is not called in this case, the instance get destroyed on scene change and due to the OnDestroy check never restored.
All you have to do is to add this line to the else branch of the singleton:
DontDestroyOnLoad(_instance.gameObject);
I tried that. I get the same error.
When the scene reloads, applicationIsQuitting is set to true as the gameobject which the ToolBox script is attached to is destroyed. And it is never reset to false. Anytime I call Toolbox.Instance, it will return null from now on and give me that warning. What happens now is I have 2 game objects with Toolbox script attached to them...one with my global vars and one without for some reason.
Am I using Toolbox wrong ?. Shouldn't I attach it to a gameobject ?
Well, it should work with DontDestroyOnLoad, however when testing in the editor there's another problem with "applicationIsQuitting". Since it's a static variable it will survive the playmode change. In a build that problem doesn't exist.
The singleton implementation should set applicationIsQuitting to false when it's created (in Awake for example but the constructor might work as well).
All in all the whole toolbox thing and it's underlying singleton class is not that well implemented.
So what's a good way if I want a global game manager kind of thing ?
Your answer
Follow this Question
Related Questions
How to create a main menu with singleton pattern? 2 Answers
Button wont run sceneloader coroutine-calling functions, but can run it's other functions 0 Answers
Does the Singleton GameObject need to be in all scenes where i need to access it? 2 Answers