Preserving Data Between Scene Loads in Unity

March 21, 2019

Advancing Tower Defense Tutorial

Moving Objects and References to New Scenes

Youtube – Unity Tutorial: Preserving Data between Scene Loading/Switching

By: quill18creates

I came across this video on preserving data between scenes in Unity when trying to find ways to cross-scene reference variables. This did not solve those issues, but it was helpful for understanding static variables and their uses better.

Static Variables: These variables become part of the class. This is what allows them to persist between various scenes. A good practice for working with these is to make them protected, so they can not be get or set. Then you just allow other scripts to affect them by calling methods within the script that contain the protected static variable.

Using static variables can lead to messy “global” style variables, or nice encapsulation. Static variables can also lead to weird errors in Unity’s Editor specifically, just because of the way it deals with classes. I am not sure if this has been cleaned up with newer versions of Unity since this tutorial is a couple years old now, but still a good thing to be aware of.

This video also went over the DontDestroyOnLoad method for persisting data. Again, this was not the solution I was looking for, but it is a good concept to learn more about.

The biggest issue you have to remember with DontDestroyOnLoad, is that if you want to go back to a scene with that object, it will create another one. There is also another issue where testing becomes more difficult. If you want something to persist, you want to delete copies of it in other scenes so there is only one at any given time. This means if you want to work on a later scene that should inherit the DontDestroyOnLoad object, it won’t be there. These issues lead to the need for a Singleton pattern.

This was their suggested Singleton pattern:

if(ThisIsTheOneAndOnlyGameStatus != null)
{
Destroy(this.gameObject);
return;
}

ThisIsTheOneAndOnlyGameStatus = this;
GameObject.DontDestroyOnLoad(this.gameObject);

This is nice because it has the added benefit of allowin you to place multiple instances of the object around your scenes to get around that problem with testing, as when two instances run into each other, the new one will always destroy itself to make sure that the one you started with persists.

Something I could replicate to make my public static instances slightly less messy, was his use of creating a public static method called GetInstance, thst simply returns the instance. This at least makes it less likely to alter the existing instance from outside its original script.