A quick tutorial on how to keep variable values stored between scenes.

This may seem like a simple thing, but unity doesn’t give any easy or clear way to complete this. Thus being a commonly asked question on help forums as people new to programming probably wont know the static keyword.

This can be simply done like so:

Create a new c# script in unity and give it a relative name such as “staticVariables”. To create these variables we need to use the keyword “static” before the Var type like so:

private static string hiderName = "hider";
private static string seekerName = "seeker";

private static int hiderScore;
private static int seekerScore;

private static int seekerGold = 500;
private static int hiderGold = 500;

private static string winner;

Calling this script on any other script is just like any other:

private StaticVars statVar = new StaticVars();

Some people may be put off by creating with “new” but as the variables use the static keyword they will remain intact. And you can use it just like any other object:

GUI.Label(new Rect(0,0,Screen.width,100), statVar.GetWinner() + " is the winner!");

As most games will return to menu on complete its best to add a reset method for such times:

public void Reset(){
	hiderName = "hider";
	seekerName = "seeker";

	hiderScore = 0;
	seekerScore = 0;

	seekerGold = 500;
	hiderGold = 500;

	winner = "";

Hope this helps some people!

Categories: GameUnity

Leave a Reply

Your email address will not be published.