[SOLVED] NullReferenceExeption - Bug in Unity?

Hi All,

In a script I’m using a static variable from another script. The app works fine, but I get this error message in every update:

NullReferenceException: Object reference not set to an instance of an object
HUD.Update () (at Assets/Scripts/HUD.cs:19)

My scripts:
Where I declaring the variables:

...
public static int score;
public static int health;
public static int money;
...
void Start()
{
score = 0;
health = 3;
money = PlayerPrefs.GetInt("Value");
...

and when I use, the another script:

...
void Update () {
TextScore.text = "" + GameManager.score; //this is the HUD.cs line 19, what seem in the error message
TextHealth.text = "" + GameManager.health;
money.text = "" + GameManager.money;
...

The last two days I tried to fix this problem, but nothing! I’m a little bit frustrated!

Thanks a lot!

What is TextScore?

1 Like

TextScore is a UI Text element, what I attached to TextScore in inspector

You need the class name you declared the static vars in, to be in front of the var.

Just make a null check for everything on that line e.g. TextScore, to find out which one causes the issue. Besides that, click on the error message. It may happen that you accidentally assigned the script to another game object. By clicking on the error message, the game object that is causing the error message gets highlighted in the hierarchy.

1 Like

It’s no bug, it means you’re referring to an object that doesn’t exist. This is a problem with your code, not Unity.

–Eric

1 Like

MEGA LIKE! I was stupid, as usual, I left the HUD script attached to an earlier game object! I removed that, and everything is fine! Thank you!!!