Why am I getting this NullReferenceException error

Hiya, I’m really scratching my head here, because I am sure the answer is embarrassingly obvious.

I am making a game that uses individual tiles/zones. I’m just building a sandbox script at the moment that essentially displays text identifying the name of the zone (same as the name of the object) when the player clicks on it.

Now the funny thing is, it actually works as intended but on each click the console logs the following error message: NullReferenceException: Object reference not set to an instance of an object ClickDetection.OnMouseDown () (at Assets/ClickDetection.cs:19)

The actual script is

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

public class ClickDetection : MonoBehaviour {

    
    public Text ident;
    
    

    // Use this for initialization

    void Start()
    {
        ident.text = ("click a zone");
    }
    void OnMouseDown()
    {
        ident.text = gameObject.name;
    }
        
 }

The error message is pointing towards the ident.text = gameObject.name; line, despite the fact it is updating the text object correctly. What am I missing!?

Outside of the script on the game object you put the ClickDetection component on, have you populated the ident Text field with something in the Inspector Window?

Alternatively, you may have wanted a line in your code to automatically assign a Text from the same game object (if it is having one) with: ident = GetComponent<Text>();

Null reference exception means that you are trying to access something that does not exist. Click on the gameobject that has this script on it. Look over in the inspector to make sure that you drag and dropped the text gameobject into the slot.

Privacy & Terms