Hi all,
I was wondering if anyone knows how to access variables in other scritps in an object? In other words, how to, from one script, change the values of another class in another script.
Preferably, I would like to access the scripts connected to a Transform, that way I can do it to the current object, or to any other object that I come across.
Thanks,
–Thomas
You can just declare a variable referencing the other script instance and assign the instance via drg&drop in the inspector.
var other : OtherScriptName;/// OtherScriptName is the name of the script
function Update ()
{
other.someVariable = 1;
}
or if you have the transform, or any component or game object.
You can use GetComponent, which gives you back the Component in the same GameObject as the receiver.
var other : Transform;/// OtherScriptName is the name of the script
function Update ()
{
var otherScript : OtherScript = other.GetComponent (OtherScript);
otherScript.someVariable = 1;
}
I am having trouble getting this to work. I have two scripts script01.js and script02.js.
In script01.js I have:
var text = "test";
function Update () {
}
and in script02.js I have
var sc : script01;
function Update () {
Debug.Log(sc.text);
}
Each script is a component of an empty gameobject. When I play the scene I keep getting the error:
System.NullReferenceException: Object reference not set to an instance of an object script02:Update ()
thanks,
Richard.
The line var sc: script01;
only declares a variable. It tells javascript that there’s a variable called sc and that it has the type script01. If you don’t assign a value to it it will be null (which is a special value, that means it has no value assigned.) This is what gives you the NULLReferenceException when you try access sc.text.
In order to assign a value to it, you will have to drag a game object containing a script01.js script onto the value in the property editor inside unity.
Perfect - it works now!
thanks a bundle,
Richard.