NullReferenceException when trying to access a variable a second time.

Hey all,

I’m trying to make a basic score system and have hit a roadblock that I can’t seem to problem-solve myself.

I’m just trying to update the text of a TextMeshProUGUI.

I have dragged the TMPro Text file in and in the Start function I update the score to the current score. It updates to 50, so that is working. However, later on, I call AddShards from another class, it adds 10 to the score and then calls UpdateShards, which in theory should update the text field again, but it gives me the error

NullReferenceException: Object reference not set to an instance of an object
ShardsScoreScript.UpdateShards () (at Assets/Scripts/ShardsScoreScript.cs:37)

Here is the code. The TextMeshProUGUI object is definitely attached as it updates in the Start function, but suddenly doesn’t exist when it tries to call the UpdateShards function…

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class ShardsScoreScript : MonoBehaviour
{
    public static int shards_count = 50;
    public TextMeshProUGUI scoreUI;
    // Start is called before the first frame update
    void Start()
    {
        scoreUI.text = shards_count.ToString();
    }

    public void AddShards(int value)
    {
        shards_count += value;
        UpdateShards();
    }

    public bool SpendShards(int value)
    {
        if (shards_count >= value)
        {
            shards_count -= value;
            UpdateShards();
            return true;
        } else
        {
            return false;
        }
    }

    void UpdateShards()
    {
        scoreUI.text = shards_count.ToString();
    }

}

Pretty new to unity, though I’ve done some other coding before. Not sure what I’m missing in this case though. Thanks in advance.

The answer is always the same… first time, second time, third time… ALWAYS!

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that