Reputation: 219
I am programming a game, and I want the text to show the player score, which increases over time. However, it is not working. Why wont it work?
#pragma strict
import UnityEngine.UI;
var score = 0;
var highScore : int;
var text : Text;
function Start() {
highScore = PlayerPrefs.GetInt("High Score");
text = GetComponent(Text);
text.text = score.ToString();
}
function Update() {
score += Time.deltaTime;
if (score >= highScore) {
highScore = score;
PlayerPrefs.SetInt("High Score", highScore);
}
text.text = score.ToString();
}
I keep getting the error:
NullReferenceException: Object reference not set to an instance of an object Timer and Scoreboard.Update () (at Assets/Scripts/Timer and Scoreboard.js:17)
Upvotes: 0
Views: 1572
Reputation: 125305
I can see that you have already assigned Text
component called Score to the text
slot in the Editor but then you override that when you did text = GetComponent(Text);
in your Start function. Simply remove text = GetComponent(Text);
and your code should work.
If you want to know why text = GetComponent(Text);
is returning null, that's because there is no Text
component attached to the-same GameObject(Main Camera) the script is attached to. text = GameObject.Find("In-Game UI/Score").GetComponent(Text);
should work fine. You don't have to do this since you have already assigned the Text
from the Editor.
Upvotes: 3