NullReferenceExcpetion [Solved]

Hi,
So I’m pretty new to C# and am currently making a game for my Uni project. I have come across this error when compiling my code and running the game:

" NullReferenceException: Object reference not set to an instance of an object
Score.Update () (at Assets/Scripts/Score.cs:19) "

This is the code in Question :

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Score : MonoBehaviour {
   
    public static int score;
    public static int lastscore;
    public Text scoreText;

    void Start () {
        score = 0;
        lastscore = 0;
        scoreText.text = "Score: 0";
    }

    void Update () {
        if (score != lastscore) {
            this.scoreText.text = "Score: " + Score.score.ToString();
        }
    }

}

Can anyone help and tell me what’s causing the error? The script updates the score on the GUI every time it’s changed.

Looks like the scoreText object has not been assigned in the inspector. Drag the text object (from the hierarchy) into the scoreText position in the inspector for this offending GameObject’s Score script.

And super kudos for using code tags on your first post!! (never seen such sanity before! :slight_smile: )

Thanks for the compliment :') But No the text has been assigned properly so I’m not sure what’s happened. I have some gui text that it’s supposed to edit and it does work but I get this error constantly in the debug menu.

Hello. I just put your script into Unity and did not get a null reference on testing and score updated properly after I assigned Text properly here in the inspector.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Score : MonoBehaviour
{

    public static int score;
    public static int lastscore;
    public Text scoreText;

    void Start()
    {
        score = 50;
        lastscore = 1;
        scoreText.text = "Score: 0";
    }

    void Update()
    {
        if (score != lastscore)
        {
            this.scoreText.text = "Score: " + Score.score.ToString();
        }
    }

}

I’m going to guess that there is another GameObject in your scene with that Script attached. Use the seach box in the hierarchy, put Score in there and you’ll see all objects that have that script attached.

Thanks for the help guys. I ended up deleting the script, putting it into a new one and then tidying up different areas of my code and got it to work!