I don’t know how to make global variables or build my own classes and use them in Unity.
I’ve seen the page speaking about using ‘static’ and then something.scriptname.variabe to access said variable outside of its own script. Didn’t work - Unity didn’t recognize the scriptname as a valid type.
Is there some page in the documentation that explains all of this? Or a wiki site?
I see people discussing it here in the forums, but I can’t find a thread where someone flat out explains how to do it in the first place (global variables or classes).
I create an empty javscript called Master_GameObject_init and attach it to my Master_GameObject. This script will contain all my global variables.
If I want to declare a global variable, I open my javascript and type the following:
static var VariableName = 0;
Don’t let the “= 0;” fool you, the code above only declares my variable, it DOESN’T give a value YET.
Next, I add a function called Awake below my variable-declaration. This function will be used to give my global variable a value, like so:
function Awake () {
VariableName = 0;
}
This can of course be anything you like it to be, string, integer, etc.
Finally, when I want to acces my global variable from another script which is attached to another gameobject, I use the code below:
//find our Master_GameObject
master_object = GameObject.Find("/Master_GameObject");
//declare the script
var master_script : Master_GameObject_init;
//connect to the script attached to our master_gameobject
master_script = master_object.GetComponent (Master_GameObject_init);
//now I can access my global variable using the code below
print (master_script.VariableName);
It’s actually simpler than that. If I have a script called “SomeScript” and it has this line:
static var aVariable = 10;
Then I can access aVariable by doing this from any other script:
SomeScript.aVariable += 20;
Remember that Unity is case sensitive, so if you find something not working as it should, check the case. Also when it said “scriptname” that meant to use the name of the script, not literally “scriptname”, which doesn’t refer to anything. (Unless you really had a script actually called “scriptname”.)