Saving Data between two Scenes in Unity

Germán Walden
3 min readApr 28, 2021

Objective: Store the difficulty info(int variable) on the Main Menu and pass it to the Game scene.

Selecting the difficulty on the Main Menu

Requisites: Two scenes and a mechanism to store the difficulty info, in this case pressing a button will make the job. C# fundamentals and Unity PlayerPrefs.

You might be wondering, what is PlayerPrefs? PlayerPrefs is a Unity class that stores Player preferences between game sessions. It can store string, float and integer values into the user’s platform registry.

This sounds very complicated but in a practical way, it allows us to carry on some data between the scenes.

In our main menu script on the menu scene, let’s say that easy is 0 and hard is 1. We want to store and update the value on the PlayerPrefs when we click on the HARD and EASY button.

We define our int difficulty variable public just for testing purposes

In the Main Menu script, we have one function for each button, let’s check the EasyButton PlayerPrefs implementation.

PlayerPrefs implementation on the EasyButton

If we go to the PlayerPrefs definition, we find that every method is static, that will allows us to save the info safely because the stored info will belong to the class and not to the object.

All available static methods from the PlayerPrefs class

What does the PlayerPrefs.SetInt() method we are using says?

Self-explanatory right?

Just in case, we are going to divide it into pieces. This function takes two parameters, a string key and an int value. The string key is the name we are giving to the stored data -> “Difficulty”. The int value is the value the difficulty variable is storing depending on what button is pressed.

Now that we know how to store info succesfully in the PlayerPrefs registry, we are done with the Menu scene and we need to retrieve this information like the image above says. PlayerPrefs.GetInt() is the chosen one.

Right into the Game scene, in our GameManager let’s define a public difficulty variable that will store the PlayerPrefs info we are going to retrieve.

PlayerPrefs.GetInt() will retrieve the information allocated in the “Difficulty” string and will be stored in the int difficulty variable that can be accessed by any other class.

In our game, we have a SpawnManager class that handles the times between waves, enemies, etc…

Here is a practical use. If difficulty is 0(easy) enemies will have their automatic spawning rate, but if it is 1(hard) it will change drastically the game

And that would be it for this tutorial, instead of retrieving the info once using PlayerPrefs.GetInt() in our GameManager, you can do it directly in any class, that’s just how you want to architecture your game.

--

--

Germán Walden

Passionate Unity developer always looking for new challenges!