# DontDestroyOnLoad() doesn't work in Unity

I have a problem with DontDestroyOnLoad() in Unity. It does not work!

My code:

private static PlayerSpawningScript instance;

public void Awake()
{
Debug.Log ("PlayerSpawningScript awake");
Debug.Log ("Instance: " + instance);
if (instance == null) {
Debug.Log ("Initializing PlayerSpawningScript instance");
instance = this;
}
if (instance != this) {
Debug.Log ("PlayerSpawningScript instance exists. Destroying new copy.");
Destroy (gameObject);
}
Debug.Log ("PlayerSpawningScript instance: " + instance);
}

public void OnDestroy()
{
Debug.Log ("Destroying PlayerSpawningSceript instance: " + instance.ToString ());
}


Basing on the console output, I successfully create an instance in scene1, but when I change the scene, it gets destroyed - I know this because I get "Destroying PlayerSpawningScript (...)" before the new scene is loaded, and the same script set up in scene2 does not find an existing instance (which held data saved in scene1) and sets up itself as the instance instead of getting Destroyed. What am I doing wrong?

• minor point that doesn't really affect anything: you don't need to say transform.gameObject you can just access gameObject directly (and indeed you do that a few lines later) – jhocking Apr 15 '15 at 15:37

Check if your gameObject has a parent object in the hierarchy.

If it has, then everything is as intended. Your object itself isn't explicitly destroyed by Unity. But its parent may very well be destroyed. It is to be expected that when an object is destroyed, all of its children are destroyed too. That's when your object is destroyed.

Put your object in the root of the hierarchy in the editor and check if the problem persists.

• Just noticed you answered your own question. Was this the solution to your tricky problem? If so, you should accept it to indicate that. – jhocking Apr 16 '15 at 12:18
• @jhocking yes :) I read on the meta that posting questions and answers documenting the problems you had is encouraged, so I wanted to share. SO didnt let me accept it for two days or so, thanks for reminding me. – K.L. Apr 17 '15 at 8:34

I seems to me that Awake is called when the object is loaded when scenes change, in that case you explicitally call destroy.

• Yes, I destroy it IF and only if there already is an instance, and this is not the case in my question. That way I can set up the script in every scene, so that I can run every scene without risking a crash because it does not have something that is instantiated in another scene. But, if I ran a scene earlier that instantiated my script and written some data to it, it is preserved, and any additional copies are destroyed, to not clutter my hierarchy/memory etc. Using a MonoBehavior instead of a regular Singleton also has it's advantages in Unity, like setting things up in the Editor. – K.L. Apr 16 '15 at 8:50
• I updated the question to address the issue you mentioned. – K.L. Apr 16 '15 at 9:01