Make a global variable that can be accessed in different scenes

Ok i have two scripts, i have one to keep track of the score in game and one script to display the script at the end. I am trying to use a static variable to store a float and display it at the endscreen, but it doesn’t work. here are the two scripts,

var Player : GameObject;
static var timer : float = 0;
var isTiming = true;
var timerSkin : GUISkin;

function OnGUI(){
	GUI.skin = timerSkin;
	GUI.Box(new Rect(10, 10, 50, 25), "" + timer.ToString("0"));
}


function Update(){
	if(isTiming == true){
	timer += Time.deltaTime;
	}
}
function OnTriggerEnter(other : Collider){
	if(other.collider.tag == Player.tag){
		Application.LoadLevel("Endscreen");
		isTiming = false;
	}
}

and

var timer : float;

function OnGUI(){
	GUI.Box(new Rect(10, 10, 50, 25), "" + timer.ToString("0"));
}

You can keep a GameObject alive through scene changes with this code:

// Make this game object and all its transform children
// survive when loading a new scene.
function Awake () {
    DontDestroyOnLoad (transform.gameObject);
}

You said you also wanted a global variable. What I’d do is probably give the mentioned GameObject a tag and do GameObject.FindGameObjectWithTag(“yourTag”), but since you asked for a global variable what you can do is make a static variable.

static var myBoolean=false;

Maybe it’s an idea to store the score in PlayerPrefs, so when you close and restart the games, it still exist.

This is an old question but the simplest way of doing it now is to use Visual Scripting. It’s a simple, new way to do it and has the added benefit of being able to be connected through graphs.

Visual Scripting, formerly, Bolt, is available from Unity 2021 onwards and you have a very wide array of options like:

  1. Application Variables - Application variables persist even when the scene changes. They are reset once the application quits.
  2. Flow Variables - Flow variables are the equivalent to local variables.
  3. Saved Variables - Saved variables persist even after the application quits. They can be used as a simple but powerful save system. They are saved in Unity’s player prefs, which means they don’t refer to Unity objects like game objects and components.
  4. Graph Variables - Graph variables are local to an instance of a script graph. They have the smallest scope and cannot be accessed or modified outside their graph.
  5. Object Variables - Object variables belong to a game object. They are shared across all graphs on that game object.
  6. Scene Variables - Scene variables are shared across the current scene.

The great thing is that these can be easily used in C# script by including the Unity.VisualScripting namespace using in your script.

They can then be accessed with:

Variables.Saved.Get("Coins"); Variables.Saved.Set("Coins:); Variables.Application.Get("Health");