Can't update score text - small error breaks the game (Space Shooter Tutorial)
I'm at the final stages of the tutorial, but now that I've tried to add the Score Text to work, I've been getting the following error:
NullReferenceException: Object reference not set to an instance of an object GameController.UpdateScore () (at Assets/Scripts/GameController.cs:49) GameController.Start () (at Assets/Scripts/GameController.cs:21)
I checked in the Inspector, and the scoreText seems appropriately assigned, but when I start playing the game, it gets switched to "None".
This is my code. What am I missing?
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameController : MonoBehaviour {
public GameObject asteroid;
public int hazardCount; // Number of hazards per wave
public float startWait;
public float spawnWait;
public float waveWait;
private int score;
public Text scoreText;
void Start()
{
scoreText = GetComponent<Text>();
score = 0;
UpdateScore();
}
public void AddScore(int x)
{
score += x;
UpdateScore();
}
void UpdateScore()
{
scoreText.text = "Score: " + score;
}
}
Answer by Oribow · Apr 25, 2016 at 01:05 PM
This line scoreText = GetComponent<Text>();
Tries to find the component Text
on the same GameObject
the script is attached to. If it doesn't find one suitable component, it returns null. That's why your scoreText
reference null, when you start the game. Just leave the line out and everything should work fine.
From Unity Scritpting API: GetComponent
Returns the component of Type type if the game object has one attached, null if it doesn't.
Your answer
Follow this Question
Related Questions
In updating some score text, why should we use the Update function instead of separate functions? 0 Answers
Is it possible for camera to detect a collision between 2 different objects it's looking at? 0 Answers
UI text script working on an object but not working on copied object 0 Answers
uGUI Text draw calls 1 Answer