0

I'm trying to create a UI in Unity using C# which displays some attributes from a player, however I am getting a NullReferenceError regarding the Text objects. I'm not sure why this is happening because there isn't anything which should be deleting these objects during runtime, and I'm fairly certain the objects are being located properly.

I have two objects being used almost identically, just for two different variables: When the program starts it locates them using:

starstxt = GameObject.Find("Stars").GetComponent<Text>();

My understanding is that this should find the text object in the scene with that name (of which there is only 1).

Then to display it:

starstxt.text = ($"Stars: {stars}");

"stars" is a variable accessed from the player.

This is the line the error is occuring on, does anyone know why? This is the only time this object is used/referenced in the program.

  • because starstxt is null. No "Stars" gameobject orelse no component inside it of type Text – J.Salas Apr 01 '22 at 09:27
  • Does this answer your question? [avoiding null reference exceptions](https://stackoverflow.com/questions/1943465/avoiding-null-reference-exceptions) – Digvijaysinh Gohil Apr 01 '22 at 09:27

2 Answers2

0

I'm guessing that the stars object you are trying to get doesn't exist or you have spelt it wrong. So you are trying to access an object that is equal to Null.

Haxor
  • 19
  • 3
0

GameObject.Find() can return null

This function only returns active GameObjects. If no GameObject with name can be found, null is returned. If name contains a '/' character, it traverses the hierarchy like a path name.

But it might not be the case because GetComponent does not throw any exception.

The problem might be that GameObject.GetComponent<> can also return null

Returns the component of Type type if the game object has one attached, null if it doesn't.

You should check whether there is anything that could make GetComponent return null according to the condition in the document.

tia
  • 9,518
  • 1
  • 30
  • 44