Data Persistance beetween scenes in Unity

Data persistance is an important aspect of creating games in unity. Sometimes, we need to save data beetween our scenes, such as player’s position or what is currently inside the player’s inventory.

For a newcomer, it might be very hard to find where the function responsible for holding Gameobjects that are persistent beetween the scenes. That is because we need to tell the engine manually that our gameobject needs to have persitance capibilities.

We can do this by inserting a script containing the following code:

public static [NameOfOurScript] GameProgressor;

void Awake() //Awake is always called first, upon start of the scene
{
if(GameProgressor == null) //checks if there's already an existing persistent gameobject to prevent duplication
{
DontDestroyOnLoad(gameObject); //assigns the persitent properties
GameProgressor = this; //assigns self to a value
}
else if(GameProgressor != null)
{
Destroy(gameObject); //destroy the other gameobject on the scene with our script, if one exists, to prevent duplication
}
}

Having this part of code allows other scripts to find your gameobject and read/write any data you desire on it. Remember however, this function is only responsible for keeping the gameobject beetween scenes, not save data beetween sessions!