- Home /
DontDestroyOnLoad Question
Hello.
I have my Game Controller set up as a singleton, however when transitioning between scenes some of the data is lost. I was under the assumption that if I use DontDestroyOnLoad() it would prevent data loss between scenes. Do I have to use this for each object I don't want destroyed and not on a single object containing other objects?
Also, if my singleton, which is static, isn't in the scene (in the editor) will it still work as expected if I use DontDestroyOnLoad() because I keep getting errors that certain GameObjects I expect to be loaded were destroyed during the scene change.
If DontDestroyOnLoad doesn't keep an entire object loaded, then what is it for? Or am I not understanding how to use it right?
For instance:
public class GameController : MonoBehaviour
{
// Game Control Objects
public static GameController GC;
// Does this stuff not stay loaded?
GameObject menu1, menu2; //....etc
void Awake()
{
if(GC == null)
{
DontDestroyOnLoad(GC);
GC = this;
}
}
}
I appreciate any help. Thanks for reading.
Answer by Fattie · Jan 26, 2016 at 12:22 PM
Yes, DDOL for EACH object you want to be DDOL.
Secondly, as a rule you should forget about Singletons in Unity or any game engine - they simply do not play with MonoBehaviours.
Instead, if you need a "singleton thing" or "singleton game object" in your game, you simply do this .. just have one of the "thing", and have some very convenient syntactic candy to access it easily from everywhere
Grid.yourMapSystem.Blah()
Grid.scoring.Blah()
Thanks alot for the answer and the advice. I was starting to think Singletons might not be a good idea since this is causing me so many problems.
Your answer
Follow this Question
Related Questions
Static variable reset at LoadLevel 2 Answers
Acessing static variable from Entities.ForEach 1 Answer
Global Variable Error 1 Answer
Will static variables not work if negative? 1 Answer
How to access a non-static variable from another class? 1 Answer