- Home /
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"));
}
Answer by Simon-Larsen · Mar 24, 2014 at 05:33 PM
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;
So if i make a static var then i could just make another script, put static var and it would be the same?
If you made a static var in one script, then you'd be able to access it through any of your scripts. Say Foo.cs has a static float coins, then Bar.cs would be able to access it as if the variable was a field of it's own instance: coins = 10.0f
Yea, I'm not sure of the javascript (Unityscript) syntax, but the idea would be the same
I for some reason can't get this to work...for a test i just made two scripts, with a static var boolean, and when you press p it switches from true to false, then i put on two different objects in two different scenes to see if it would even work. But when i did that i can't even see the boolean in the inspector. I dunno
Answer by Flux · Mar 24, 2014 at 05:36 PM
Maybe it's an idea to store the score in PlayerPrefs, so when you close and restart the games, it still exist.
https://docs.unity3d.com/Documentation/ScriptReference/PlayerPrefs.html