using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class NewBehaviourScript : MonoBehaviour
{
public TextMeshProUGUI countText;
private int count;
void Start()
{
count = 0;
SetCountText();
}
void SetCountText()
{
countText.text = $"Score: {count}";
}
}
Accessing countText
triggers NullReferenceException. None of the solutions offered online work. What is even more suspicious is the fact code is taken from official unity tutorial. I suppose someone made a mistake.
Some additional info: how it looks like in unity ui CountText settings
Everything seems to be in order.
CodePudding user response:
The Debug class provided by unity is a helpful tool, and should be used extensively during your games development.
Debug.Log($"My object is {myObject}");
Some references are set during design time using the Inspector
window.
These references must be set before entering play mode, otherwise they will be null
. You can set the reference by dragging an object of that type onto the object field in the inspector.
A null reference will happen when you attempt to access a member of a null object.
public class DisplayPlayerName : MonoBehaviour
{
public TextMeshProUGUI uiName;
public GameObject player;
void Start()
{
uiName.text = player.name; // <- whoops! NullReferenceException
}
}
In the example above, if either uiName
or player
are not set in the inspector, a null reference exception will be thrown. This is because we are accessing a member of each of those objects. We want to set the text
property of uiName to the name
property of player.
But how do we know which one game object is causing the problem? I have a million gameobjects and don't want to check them all!
Tricks to help narrow your search
Debug the name of the object that threw the exception.
if (player == null ||
uiName == null) // <- do some null checking
{
Debug.Log($"{name} has null player or ui"); // <- log the gameobjects name
return; // <- exit the function
}
// This won't throw the exception anymore because we exit the function when null is detected
//
uiName.text = player.name;
Logging the objects name is most helpful when we name every object (or at least the most important ones) in a meaningful way.
You can filter the objects in your scene to those that have a specific component on it. Using the search bar in the Hierarchy
window, type t:
followed by the name of your component eg. t:DisplayPlayerName
. This will show only the objects that have that component attached.
Hopefully this provides you with some new tools for debugging in unity.