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

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

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.

Conclusion

Just a student at flatiron

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store