NullReferenceException in Unity despite added script as a component

Viewed 50

My code throws an error:

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

This is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using static System.Net.Mime.MediaTypeNames;

public class scoreScript : MonoBehaviour
{

    /* the text object we want to edit the text of (there are two different types of text in unity so it needs to be specified */
    UnityEngine.UI.Text scoreText;
    public static int chocAmount; //amount of chocolate eaten


    // Start is called before the first frame update
    void Start()
    {
        // UnityEngine.UI.Text scoreText = (UnityEngine.UI.Text)gameObject.GetComponent<UnityEngine.UI.Text>();
        scoreText = GetComponent<UnityEngine.UI.Text>();

    }

    // Update is called once per frame
    void Update()
    {
        scoreText.text = "x " + chocAmount.ToString();
    }
}

The exception is thrown for line 26:

scoreText.text = "x " + chocAmount.ToString();

And yes, I did add the script to a Text-UI-Object:

Components of UI gameobject Components of UI gameobject

2 Answers

If you have attached TextMeshPro-Text component to a gameobject you have to get the same via script, Here the component you are getting in script mismatches with the component you have attached.

UnityEngine.UI.Text

is simply the wrong type.

What you want / have attached to your object is a

TMPro.TextMeshProUGUI

or the more generic

TMPro.TMP_Text
Related