- Home /
Changing variable from another script
Hello, I'm getting an error which I do not understand when trying to change a variable from a script to another script on collision. I have a score UI that always rises, and I want it to reset to 0 when it hits a certain GameObject.
The error I'm receiving is:
NullReferenceException: Object reference not set to an instance of an object CollisionDetect.OnCollisionEnter (UnityEngine.Collision theCollision) (at Assets/MyScripts/CollisionDetect.js:25)
CollisionDetect:
function OnCollisionEnter(theCollision : Collision){
if (theCollision.gameObject.name == "HighWall(Clone)")
{
Debug.Log("Hit the " + theCollision.gameObject.name);
var script1: ScoreGUI = GetComponent(ScoreGUI);
script1.Counter=0;
}
if (theCollision.gameObject.name == "HighWall2(Clone)")
{
Debug.Log("Hit the " + theCollision.gameObject.name);
var script2: ScoreGUI = GetComponent(ScoreGUI);
script2.Counter=0;
}
ScoreGUI:
var Counter: float=1.0;
function Update(){
Counter=Counter+1.0;
}
function OnGUI(){
GUILayout.BeginArea ( Rect ( 10, 10, Screen.width / 4, Screen.height / 4 ) );
GUILayout.Box (Counter.ToString () );
GUILayout.EndArea ();
}
Thanks,
I'm guessing you want to be calling GetComponent on the thing you hit? Perhaps on something else? There are a few tutorials on Unity Gems about using get component and some common Gotchas
Answer by greatestprez · Nov 23, 2012 at 03:56 AM
Instead of directly changing the variable you use the SendMessage() function.
How would I do that exactly? I'm still new to scripting in Unity.
Just a note: Send$$anonymous$$essage is 85 - 150x slower than calling a function directly.