Access variables from another script (26054)

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.

3 Answers

3

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.

@Facepalm, if this was a comment to my answer, please use Comments. :-) - answers are answers to the question.

–

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.

A script IS a class. Of type "MonoBehavior", actually.

–

Oh... I see Scripts written in javascript don't declare the classname, like C# ones do. My mistake. They're still classes, they just seem to be inheriting the filename, I suppose. You're absolutely sure those two scripts are attached to the same gameobject?

–

Okay. That's... odd. Just for fun and giggles, try to use the non-generic version of GetComponent instead, and try to explicitly grab the gameobject that it is attached to, using Find, i.e. try this: GameObject.Find("WhateverThatGameObjectsNameIs").GetComponent("Movement").direction, and see if that returns the proper script. I know this is slower, I'm just curious.

–

@sacredgeometry Hey mate, I figured it out through profiler. I updated the question so you can see what I found out above.

–

Hi! Change your Collison.js to this

Collison.js

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
}

}