Any variable defined outside of any function defines a member variable. The variables are accessible through the inspector inside Unity. Any value stored in a member variable is also automatically saved with the project.
var memberVariable = 0.0;
The above variable will show up as a numeric property called "Member Variable" in the inspector.
If you set the type of a variable to a component type (i.e. Transform, Rigidbody, Collider, any script name, etc.) then you can set them by dragging game objects onto the value in the inspector.
var enemy : Transform;
function Update() {
if ( Vector3.Distance( enemy.position, transform.position ) < 10 )
print("I sense the enemy is near!");
}
You can also create private member variables. Private member variables are useful for storing state that should not be visible outside the script. Private member variables are not saved to disk and are not editable in the inspector. They are visible in the inspector when it is set to debug mode. This allows you to use private variables like a real time updating debugger.
private var lastCollider : Collider;
function OnCollisionEnter(collisionInfo : Collision ) {
lastCollider = collisionInfo.collider;
}
Global variables
You can also create global variables using the static keyword.
This creates a global variable called someGlobal.
// The static variable in a script named 'TheScriptName.js'
static var someGlobal = 5;
// You can access it from inside the script like normal variables:
print(someGlobal);
someGlobal = 1;
To access it from another script you need to use the name of the script followed by a dot and the global variable name.print(TheScriptName.someGlobal);
TheScriptName.someGlobal = 10;