reference to TextMeshPro

Hi,
I’m trying to create a score system in Unity 2021.1.7

    public TextMeshProUGUI scoreText;


void Start()
    {  
        score = 0;
        Debug.Log("scoreText found");
        scoreText.text = "Score: " + score;
    }


   public void UpdateScore()
    {
        score += 10;
        Debug.Log(score);
        scoreText.text = "Score: " + score;
    }

I dragged and dropped the TextMeshPro object from the hierarchy to the Inspector.

UpdateScore is called in another function. When I hit play, the zero appears for “Score:0”, so it “works”. but I also get the error message:
“NullReferenceException: Object reference not set to an instance of an object
GameManager.Start () (at Assets/_scripts/GameManager.cs:18)”
Line 18 is the first use of" " scoreText.text = “Score: " + score;” So this line works to put the zero in the on screen text but also throws the error message.

in UpdateScore the Debug,Log prints the correct score but the on screen text does not update and again the Null reference exception error is given.

How do I fix this?
Why is the first example working while throwing an error?
Thank you for your help.

It is irrelevant what you are doing. The answer for null reference is always the same… ALWAYS. It is the single most common error ever.

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

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

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

This is the kind of mindset and thinking process you need to bring to this problem:

https://discussions.unity.com/t/814091/4

Step by step, break it down, find the problem.

Here is a clean analogy of the actual underlying problem of a null reference exception:

https://discussions.unity.com/t/840647/7

1 Like

For what it’s worth I didn’t find the problem but rebuilding it from scratch worked.

Thank you for the great process to find future errors. Debug.Log is my friend.

1 Like