A little help with an Object Reference error

I sort of need a bit of help. Some weird Object reference error keeps popping up, and I’m not sure what to do (I’m very new to Unity btw)

public HealthBar healthBar;
public int Maxhealth = 3;

void Start()
{
currentHealth = Maxhealth;
healthBar.SetMaxHealth(Maxhealth);
{ }
}

public int currentHealth;

void TakeDamage(int damage)
{

currentHealth -= damage;
healthBar.SetHealth(currentHealth);
if (currentHealth <= 0)
{
Application.LoadLevel(Application.loadedLevel);
}
}

The HealthBar script is here:

public Slider slider;

    public void SetHealth(int health)
    {
        slider.value = health;
    }
    public void SetMaxHealth(int health)
    {
        slider.maxValue = health;
        slider.value = health;

    }

Any help would be appreciated!

On which line does the error appear ?

Are that empty { } in the start method in your code ? If yes, you should remove them.

Sharing the error message you’re getting (in whole) would be a good first step.

Is it a compile-time error, or a runtime error?

The errors occur with these lines:

healthBar.SetMaxHealth(Maxhealth);
healthBar.SetHealth(currentHealth);

And in the HealthBar script:

slider.maxValue = health;

If I remove this code, my game functions fine, but it doesn’t seem to work even though I followed a tutorial D:

(A runtime error)
To be precise, this is the message log:

NullReferenceException: Object reference not set to an instance of an object
HealthBar.SetMaxHealth (System.Int32 health) (at Assets/HealthBar.cs:17)
PlayerHealth.Start () (at Assets/PlayerHealth.cs:13)

That error happens when you haven’t assigned a value to your fields. In this case, your “healthBar” and “slider” fields. To assign those values you need to drag the appropriate objects from your scene into those fields in the inspector for your script.

1 Like

I figured out what went wrong. I forgot to assign the slider value. Thank you for helping me!

Glad you got it going, but it is always the same answer and approach for this problem:

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.