NullReferenceException: Object reference not set to an instance of an object

I am a new Unity gamemaker and I’m trying to create a simple sorting game. I just added the code supposed to change the score when touching platforms, and when I run the game, the score does not update, and this error persists:
NullReferenceException: Object reference not set to an instance of an object
Score.Update () (at Assets/Score.cs:10)
How do I fix the code to make it so the score updates and this error goes away?
Score.cs (Inside Text element, defines score variable and displays)

using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
    public float score = 0f;
    public Text scoreText;
    // Update is called once per frame
    void Update()
    {
        scoreText.text = score.ToString();
    }
}

BlueCollide.cs (Inside ball, supposed to change score variable)

using UnityEngine;

public class BlueCollide : MonoBehaviour
{

    void Start () {
        GameObject Text = GameObject.Find("Text");
            Score scoreSc = Text.GetComponent<Score>();
    }

        void onCollisionEnter (Collision collision) {

            if(collision.collider.name == "Blue") {
            scoreSc.score ++;
        }
        if(collision.collider.name == "Orange") {
            scoreSc.score --;
        }
    }
}

Help would be greatly appreciated. Thanks!

1 Like

Hey, as the error implies, a reference you are using is null. This simply means it does not exist, ie was not yet assigned, since been removed, or deleted. The line referenced in the error tells you where the problem is occuring. It’s line 10 in the Score script. At line 10 you write ‘scoreText.text = score.ToString()’. Your ‘scoreText’ is null, hence when the compiler tries to access ‘null.text’, which does not exist, it thorws a NullReferenceException.
You probably forgot to set scoreText in the inspector.

4 Likes

How to fix a NullReferenceException in Unity3D:

http://plbm.com/?p=221

The errors are gone, thanks!

1 Like