Calling variables in external script - weird results

Ive got a game-state script where I initialize and update variables that are “global”.

Game_State.js

var globalVariable_1 = "hello";  // string
var globalVariable_2 = 20;  // number
var globalVariable_3 = false;  // bool

Other_Script.js

private var Game_State : scr_Game_State;
function Start () {
	Game_State = FindObjectOfType(scr_Game_State);	

	Debug.Log("globalVariable_1 = " + Game_State.globalVariable_1);
	Debug.Log("globalVariable_2 = " + Game_State.globalVariable_2);
	Debug.Log("globalVariable_3 = " + Game_State.globalVariable_3);
}

Output:
globalVariable_1 = hello
globalVariable_2 = 1
globalVariable_3 = true

As you can see, the output is correct only for the string-type, but when initializing numbers or booleans the value retured is incorrect.

Can anybody make sense of this, and hopefully propose a solution?

Most likely you’ve overridden those values in the inspector.

If you’re using global variables, just declare them as static. They don’t show up in the inspector, you don’t have to attach your Game_State script to anything, and you don’t have to use FindObjectOfType or GetComponent to access them:

Game_State.js:

static var globalVariable_1 = "hello";

Other_Script.js:

Game_State.globalVariable_1 = "Goodbye";

Thats pretty cool - and it works perfectly. Thanks a lot!

However, is there a way to make those static variables appear in the inspector? Kinda nice to change them via that pane, or at least view them. Nothing crucial, though, I can live without it :slight_smile:

Generally you’d have to write a custom editor to get static variables to appear in the inspector.

But if you just want to initialize the values, you could write an initialization script that has public variables and then during Awake() set your static variables to those:

var startingLives = 3;

function Awake(){
    GameState.lives = startingLives;
}