NullReferenceException: Object reference not set to an instance of an object

Hi everyone,

I am trying to create a progress bar. I’m using the SimpleHealthBar from the asset store. I’ve created a healthbar object and created a script to display the score. However, I keep getting NullReferenceExceptions. I’ve tried everything I could think of, but I can’t get rid of it. Could somebody please shed some light on this?

Eternal thanks!

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class DisplayScore : MonoBehaviour
{
    public Score score;
    public SimpleHealthBar healthBar;
    public float duration;
    public float delay = 0f;
    public string prefix;
    public float currentDisplayScore = 0;
   
    int maxProductivity = 100;
    int maxEntertainment = 100;
    int maxOrganisation = 100;

    int steps = 5;
    void Start()
    {
        healthBar.UpdateBar(50, 100);
    }
}

The full error message is:
NullReferenceException: Object reference not set to an instance of an object
DisplayScore.Start () (at Assets/Scripts/DisplayScore.cs:23)

Verify you don’t have an extra instance of DisplayScore in your scene accidentally. You can add debugging to the beginning of Start to display the name of the GameObject the script is attached to.

Also verify you are not setting healthBar to null from some other script, and that you are not destroying the object or component. Check whether it is null in play mode, add debugging.

Thanks, you were right! Turned out I had the same script on another object that I forgot about.

1 Like