Please help regarding NullReferenceExpection

Hello everyone, I was wondering if someone could help me on finding why I’m receiving such an error. It appears that in order to access the next level, I must press the continue button twice. Therefor I think it has to be related to score.SendMessage (“Reset”);

Thanks in advance!

#pragma strict

var scorePrefab: Transform;

function OnGUI () {

if (GUI.Button (Rect (540,500,200,80), “Continue”)) {

var score: GameObject = GameObject.FindWithTag("Score");
if (!score) {
	
	GameObject.Instantiate(scorePrefab);
}

score.SendMessage ("Reset"); 
Application.LoadLevel (3);
}

}

I’m guessing it’s not finding the score object the first time, so it’s instantiating it, then you send a message to a null reference because it never found it and the thing you instantiated was never accessed by your code…

try :

//..........//
if(!score){
   score = instantiated score stuff ;
}
score.sendmessage etc..
//....//

The first thing you should try is to add some Debug.Log statements to see if you actually get anything the first time you find the score object.

My guess on what’s happening is that the first time the button is pressed, there isn’t actually an object with the tag “Score”, so you instantiate one. The second time, after making one, there is an object with the tag “Score”

Your actual problem though, comes from the “score.SendMessage()” line, because at that point, score may exist from where you set it at the beginning, or it may not. (If you go into that if statement, score never exists, so when you call sendmessage, there’s nothing to send it to.)

To fix it, just set score in the if statement:

 score = GameObject.Instantiate(scorePrefab)

(You may have to use the var score : GameObject syntax, I’m not as familiar with JS)