How to share data between different JavaScript files

I have a variable “a” in A.js. Like function Update() {a;}
And I want to change “a” in B.js.
Is there anybody who can tell me what I should write in A.js and B.js?

Thanks a lot!!!

There are at least two easy ways of doing it. Sharing variables is pretty straight forward in these cases.


//Static variable in script A
static var variableInScriptA : int = 1;

//Call from script B to script A
variableInScriptB = scriptA.variableInScriptA;


//Calling a public variable in script A from script B
var scriptA : ScriptA; //Assign the object with the script named ScriptA in Inspector
private var variableInScriptB : int = 0;
function Start () {
    variableInScriptB = scriptA.variableInScriptA;
}

//Where the public variable in script A is declared:
var variableInScriptA : int = 1;

You’re also able to do the second example at runtime by getting the component of an object and point to the script, this is handy if you don’t know yet which object’s script is going to be accessed.

function OnTriggerEnter (other : Collider) {
    var scriptA : ScriptA = other.gameObject.GetComponent(ScriptA);
    if (scriptA!=null) {
        scriptA.someBooleanVariable = true;
    }
}

Note that you won’t be able to access private variables from other scripts. They are secluded from anything outside the class/script.