NullReferenceException: Object reference not set to an instance of an object. Even if obj not null

Hi,
I am trying to change my TMP_Text component’s text. I’m getting an error that I can’t understand. Because the textCounter object is not null.

Here is a sample:

private TMP_Text textCounter;

void Start()
{
  print("Start"); 
  textCounter = transform.Find("Canvas/TextCounter").GetComponent<TMP_Text>();
  print("Start Finished");
}

void SetText()
{
  print("set text");
  textCounter.text = "text"; // null reference exception.
}

// This is how I call the method from a different script.
// BasketController.instance.SetText();

Here is some screenshots:

textCounter assigned in start method.
8451206--1121129--upload_2022-9-20_1-49-29.png

Script already initialized before I call it.
8451206--1121132--upload_2022-9-20_1-50-59.png

I realized that I had made a very fundamental mistake. I noticed that the methods of the objects I instantiate do not work because I call them with instance.

My mistake is the comment line on line 19.

This might help you reason about timing for setting stuff like instances:

https://docs.unity3d.com/Manual/ExecutionOrder.html

For instance-y type static locators, I like this pattern:

Simple Singleton (UnitySingleton):

Some super-simple Singleton examples to take and modify:

Simple Unity3D Singleton (no predefined data):

https://gist.github.com/kurtdekker/775bb97614047072f7004d6fb9ccce30

Unity3D Singleton with a Prefab (or a ScriptableObject) used for predefined data:

https://gist.github.com/kurtdekker/2f07be6f6a844cf82110fc42a774a625

These are pure-code solutions, do not put anything into any scene, just access it via .Instance!

If it is a GameManager, when the game is over, make a function in that singleton that Destroys itself so the next time you access it you get a fresh one, something like:

public void DestroyThyself()
{
   Destroy(gameObject);
   Instance = null;    // because destroy doesn't happen until end of frame
}

Finally, just for completeness, I’ll post the three steps too:

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null
  • Identify why it is null
  • Fix that
1 Like