DontDestroyOnLoad resetting variables

The following code:

public class Client
{
private bool hasStarted;

void Awake()
{
   print("Has Started ? " + hasStarted);
   hasStarted = true;
   DontDestroyOnLoad(transform.gameObject);
}

void OnLevelWasLoaded(int level)
{
    print("Level Load:  hasStarted = " + hasStarted);
}

}

At ever scene load has started is reset to true. I have tried the following variations separately and in combination all to no avail.

  1. DonDestroyOnLoad(this);
  2. DontDestroyOnLoad(GameObject.Find(“Client”));

NOTE: the name of the prefab to which this script is attached is named Client.

In every case it resets hasStarted to false;

Am I missing something? Shouldn’t a class variable retain its value if the script really IS not being destroyed? I read in the answers something about cloning the object, but then it really IS destroyed and thus this is a new script and I want the old one.

1 Answer

1

I found the problem. I had mistakenly (earlier in my development) copied this asset into each scene so that the script would be there. I later added the dontdestroyonload and it wasn’t until I started testing jumping from scene to scene I noticed the error. I just had forgotten by then that I had added the assets to each scene smacks forehead