I want to change the text of a 3dText accordingly to the player’s points.
I have this script but it doesn’t work. It gives me these errors:
NullReferenceException: Object reference not set to an instance of an object
System.Int32.ToString () (at /Applications/buildAgent/work/3df08680c6f85295/mcs/class/corlib/System/Int32.cs:672)
Test.Start () (at Assets/Test.js:9)
Are you sure the TextMesh was actually found? Or the other component you were looking for with .GetComponent(…)?
Those are the two obvious tracks to follow. In cases like this put a breakpoint in a line just before the first search operation.
function Start(){
// This can return null, put a breakoint in this line
var txtScore = GameObject.Find("TextScore");
if (txtScore)
{
var textandpoints : TextMesh = txtScore.GetComponent(TextMesh);//Here
var script1 : ScoreHolder = txtScore.GetComponent("ScoreHolder");//Here
textandpoints.text = script1.scoreHold.ToString();
}
}
It could be textandpoints.text giving you the null reference exception, or the script1.scoreHold because of either textandpoints or script1 being null.
Note: When using monodevelop always put a breakpoint in the line that “does something”, it’ll be a filled circle (as oposed to lighter fill color when breakpoint is put on, for example, a bracket line)
I have reproduced it, and I have to admit this is the most confusing NullReferenceException I have ever seen…
The problem is related to the fact, that in this line:
var script1 : ScoreHolder = txtScore.GetComponent("ScoreHolder");
no component is returned, so script1 is null. You probably forgot to add ScoreHolder script to your TextScore object. Btw - I suggest using txtScore.GetComponent(ScoreHolder) (with type parameter instead of string).
And regarding my confusion - I don’t understand the stack trace, suggesting that error occurred inside Int32.ToString() method. In normal .NET application, exception would be pointing simply at line 9 of your script, because script1.scoreHold part would cause exception.
EDIT: btw - in opposite to other answers/comments, there is no need to initialize scoreHold to 0. int is value type, initialized to 0 by default.