Hi! Im trying to access variable from different script attached to the same object, but its not going well for me. Example of what I have at the moment:
Movement.js
var direction = 1;
function Update () {
...
}
Collision.js
var go : GameObject;
function OnTriggerEnter (other : Collider) {
var temp = GetComponent(Movement).direction;
if (...){
Destroy(go);
}
}
With such code I receive an error “NullReferenceException: Object reference not set to an instance of an object” on the line “var temp = GetComponent(Movement).direction;”. Please tell me, what should I do to fix it because I tried different codes based on examples given in the Unity Script Reference and no one worked.
You need to initialize the go object with an object from the Scene. Either by program or by using in the inspector panel and then selecting one of the active stage objects manually.
It's not the variable go, since the NullReferenceException occurs before he's calling Destroy(go).
This doubtlessly happens because there is no script instance called Movement attached to this gameobject. If you're perfectly sure the script is attached, then check the file Movement.js, and verify that the classname is indeed "Movement". Remember, with GetComponent, you are searching for the classname. Not the filename. You can't add a script to an object whose classname differs from its filename, but it's possible to add it while they match, and then mistakenly change the classname afterwards. This breaks things.
var go : GameObject;
//Here we define the script you want to acces
//In your case its Movement.js
private var script : Movement;
function Awake(){
script = GetComponent(Movement);
}
function Update(){
//Now you can simply acces any variable from Movemeny.js by adding script before
//any variable, like so
if(script.direction == 2){
//Do something
}
}