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;
DontDestroyOnLoad (gameObject);
}
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 Destroy
ed. What am I doing wrong?
transform.gameObject
you can just accessgameObject
directly (and indeed you do that a few lines later) \$\endgroup\$