Unity & Javascript also allow us to define global variables. These are variables that will be available to *all* scripts within your game. We define global variables by using the “static” keyword. Let’s see an example.
Save this script as “globalExample”.
static var myFirstGlobal : String;
function Awake () {
myFirstGlobal = "This string is available throughout my game!";
}
Create another script and call it whatever you like.
function Start () {
//we use the name of the script where the variable was defined to access the global variable
//prints "This string is available throughout my game!" to the console
print (globalExample.myFirstGlobal);
//assign a new string to the variable
globalExample.myFirstGlobal = "This variable was changed from outside the script it was defined in!";
}
Pretty handy right? We created one script and defined a global variable, then we accessed that variable from another script. When creating games it’s essential that you’re scripts can communicate with each other in one way or another. Taking advantage of variable scope is one way to accomplish this. So when you’re creating variables within your scripts, ask yourself “Am I going to need to access this variable anywhere else?”.
Common Variable Types in Unity 3
When defining a variable, its good practice (and often a requirement) that you define it’s type as well. You’ll find yourself using a few type of variables more often than not. Defining variable types also helps to speed up processing and proper use of variable types helps avoid conflicts and helps keep memory usage in check.
//define a floating point variable (floats can hold integers with or without decimal points)
var firstFloat : Float = 1.0;
//define an integer - an integer is a positive or negative number with no decimal points
var firstInteger : int = 10;
//define a string - a string can contain both next and numbers but can't be numerically compared without first being processed
var firstString : String;
//define a boolean - booleans hold a value of either ***e or false (1 or 0)
var frstBoolean : Boolean;
//define a Vector3 - a Vector3 holds a set of 3 float values or integers (0,0,0)
var frstVector : Vector3;Javascript Dynamic Variable Typing
when declaring variables in C# you *must* define the type of variable for every variable you create. The same does not hold ***e for Javascript however, which is one reason it’s much easier to pick up than C#. Javascript uses what’s called “dynamic variable typing”. In other words, when you define a variable Unity will *guess* at what the type should be when you assign a value to it. Unity can’t always guess correctly, but it will try it’s best to “dynamically type” the variable. Keep in mind, using dynamic typing is costly in terms of overhead and isn’t very good practice – but it’s still handy to know that the option is there.