Question by
Blademaster680 · Oct 11, 2015 at 12:08 PM ·
script error
Script Error: Object reference not set to an instance of an object
Hi
I am new to Unity and I was wandering if any of you could help me with my problem. I am using a script when the player dies to display their score etc etc. The error that comes up says "Object reference not set to an instance of an object" I cant see why it would be saying, I have searched all over the place and cant seem to fix it.
The error is on line 15:
scoreText.text = "Score: " + score;
Here is the full script:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class GameOverScript : MonoBehaviour {
int score = 0;
Text scoreText;
// Use this for initialization
void Start ()
{
score = PlayerPrefs.GetInt("Score");
scoreText = GetComponent<Text>();
scoreText.text = "Score: " + score;
}
void Update ()
{
}
public void ReryButtonPressed ()
{
Application.LoadLevel("Level");
}
public void MainMenuButtonPressed()
{
Application.LoadLevel("MainMenu");
}
}
If anyone could please help me, it would be much appreciated.
Comment
Answer by Linus · Oct 11, 2015 at 12:13 PM
Object reference not set to an instance of an object means that scoreText is null. In other words the game object this script is on does not have a Text component.
Here is a simple alternate solution.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class GameOverScript : MonoBehaviour {
int score = 0;
public Text scoreText; // ####### Drag the gameobject with label on to here
// Use this for initialization
void Start ()
{
score = PlayerPrefs.GetInt("Score");
scoreText = GetComponent<Text>();
scoreText.text = "Score: " + score;
}
public void ReryButtonPressed ()
{
Application.LoadLevel("Level");
}
public void MainMenuButtonPressed()
{
Application.LoadLevel("MainMenu");
}
}