Null Reference Exception - Realm Rush

Hello. Been following along the Realm Rush section. Working on the grid and setting that up.
Had it working, closely resembling Gary’s. Had the Null Reference exception once prior, but that was because I tried simply apply it by sliding it onto the text, but it applied the script to the cube.

After fixing my error, it showed the coordinates and was working correctly until I tried to do the “play” test he did to see what would happen. After that, the coordinates were broken. Found out that it disabled the Script. But turning it on now gives a Null Reference Exception.

NullReferenceException: Object reference not set to an instance of an object
Coordinates.DisplayCoords () (at Assets/Scripts/Coordinates.cs:29)
Coordinates.Update () (at Assets/Scripts/Coordinates.cs:21)

is the error and location is line 29:coords.text = coordinates.x + " , " + coordinates.y;

1   using System.Collections;
2   using System.Collections.Generic;
3   using UnityEngine;
4   using TMPro; //Gives access to the text mesh pro asset
5   using System;
6
7   [ExecuteAlways]
8   public class Coordinates : MonoBehaviour{
9   // Start is called before the first frame update
10  
11    TextMeshPro coords;
12    Vector2Int coordinates = new Vector2Int();
13  
14    void Awake(){
15       coords = GetComponent<TextMeshPro>();
16    }      
17 
18
19    void Update() {  
20       if(!Application.isPlaying){
21            DisplayCoords();
22       }   
23    }
24  
25    void DisplayCoords(){
26       coordinates.x = Mathf.RoundToInt(transform.parent.position.x);
27       coordinates.y = Mathf.RoundToInt(transform.parent.position.y);
28       
29       coords.text = coordinates.x + " , " + coordinates.y;
30    }
31  }

I’m not seeing why it’s Null Referencing.

Hi,

NullReferenceException means that a reference (“link”) to an instance is missing.

Since coordinates is of type Vector2Int, which is a struct, that variable can never be null. The only other variable in line 29 is coords, so the NullReferenceException is very likely referring to coords.

Check if there is a TextMeshPro component attached to the same game object as the Coordinates script. If there isn’t, GetComponent<TextMeshPro>(); will return null.

It might be that Awake does not get called if the game is not running. In that case, I would suggest to move the code from the Awake() method to DisplayCoords(). For reasons of performance, check coords for null with an if-statement so GetComponent<TextMeshPro>(); gets executed only if coords is null.

Did this fix it for you?


See also:

1 Like

So it was actually nothing? Loaded up unity to find the issue and it just was working again. Thank you though

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms