Null reference exception

I am getting an error on my Mouse world Position no i dea what it is but it keeps repeating . game plays fine but the error is concerning


The error is in your GridDebugObject on line 21 in the Update method.
Paste in your GridDebugObject.cs and we’ll take a look.
Rather than pasting in a screenshot of the code, before pasting in the code type the backwards apostrophy three times on it’s own line. At the end of the code, type those three apostrophes again.
```
Type code here
```

1 Like

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

public class GridDebugObject : MonoBehaviour
{
    [SerializeField] private TextMeshPro textMeshPro;
    private object gridObject;
   
    public virtual void SetGridObject(object gridObject)
    {
        this.gridObject = gridObject;
    }

    protected virtual void Update()
    {
        textMeshPro.text = gridObject.ToString();
    }
}

I went ahead and edited the code, adding the ``` and removing the extra space the editor puts between lines if you don’t paste it in a ``` code block. Take a look at it by Editing the post, and you’ll see where I put the ```

On to the error… there are actually two possibilities… either gridObject has not been saved (i.e. SetGridObject() hasn’t been called, or the textMeshPro wasn’t set in the inspector.

Let’s add this to Update:

protected virtual void Update()
{
    if(textMeshPro==null)
    {
         Debug.Log($"TextMeshPro was not set on the prefab");
         return;
     }
     if(gridObject==null)
     {
          Debug.Log($"gridObject has not been set.");
          return;
     }
     textMeshPro.text = gridObject.ToString();
}
1 Like

Thanks a bunch

Privacy & Terms