Passing Data between different Scenes in Unity (Static Variable)
There are many ways to pass data from one scene to another inside Unity.
- Using Static Keywords
- Using DontDestroyOnLoad function
- Saving to local storage(file) and load inside another scene.
- Using ScriptableObject
Today I want to showcase the easiest method of them all, using Static Keyword.
Public vs Private vs Static Variables
There are three types of variables in unity.
Public Variables are variables that can be accessed from other classes. Which allows other game scripts to grab variables from this script, and they are allowed to manipulate it however they want.
Private Variables are variables that can only be accessed from within the class itself. This is the most secure type of variables since other scripts cannot change it, unless the script itself creates public functions that access the variable itself.
Static Variables belongs to the class it self, instead of a single instance. This allows anyone from anywhere to grab the variable, and modify it however they want.
Using Static Variables to Transfer Data in Unity
We can start with an simple example, let’s create a variable which will keep track of the time we spent between scenes.
Lets start with Creating a Scene in Unity. We create an empty GameObject called GameManager. This will be where we store the scripts that needs to be run. We’ll also create a button to change between Scenes, and a text called Time which contains the variable we are transferring between Scenes.
First create a C# file StaticVar to keep track of any information we need between scenes. We can also write a simple update to increase the number as time passes.
We’ll also write a simple C# file for the button to change between scenes.
Then we attach both script to the GameManager that we created earlier.
Next on the button we’ll add in a on click function which will trigger our function to load another Scene.
Let’s also create another script called ShowTime for the text to show the current time variable from our StaticVar. Attach the new script to the Time text game object.
Last we’ll create a second scene with similar setup as scene one, except I’ll add in an addition unity UI text object to show that this is the second scene. Make sure the GameManager have the same script added same as the other scene.
Now everything work click play and watch the Time Variable gets updated and is in sync between both scenes.
Due to fact that it can be accessed and changed easily by other scripts, Static variable isn’t all that safe to transfer data around. However it is easy and one of the fastest method to implement in Unity to transfer data around.