- Home /
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);
}
}
Answer by Lo0NuhtiK · May 14, 2012 at 03:03 PM
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..
//....//
Thanks for the replay but this doesn't solution doesn't work, anyway I've decided to just leave the error since it doesn't effect my game.
Thanks though!
Hope you didn't try copy/pasting the code above, obviously that wouldn't have worked.
Answer by perchik · May 14, 2012 at 03:04 PM
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)
Hey thanks for the replay, yeah it appears that the problem does indeed come from the score.Sendmessage line, I've changed however another error pops up, anyway as long the game is functional I'm happy with it.
Thanks though!