Search Unity

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

Discussion in 'Scripting' started by timtbruyn, Dec 17, 2019.

  1. timtbruyn

    timtbruyn

    Joined:
    Dec 17, 2019
    Posts:
    3
    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! unity_with_highlights.png

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. using System.Collections;
    4. public class DisplayScore : MonoBehaviour
    5. {
    6.     public Score score;
    7.     public SimpleHealthBar healthBar;
    8.     public float duration;
    9.     public float delay = 0f;
    10.     public string prefix;
    11.     public float currentDisplayScore = 0;
    12.    
    13.     int maxProductivity = 100;
    14.     int maxEntertainment = 100;
    15.     int maxOrganisation = 100;
    16.  
    17.     int steps = 5;
    18.     void Start()
    19.     {
    20.         healthBar.UpdateBar(50, 100);
    21.     }
    22. }
     
  2. timtbruyn

    timtbruyn

    Joined:
    Dec 17, 2019
    Posts:
    3
    The full error message is:
    NullReferenceException: Object reference not set to an instance of an object
    DisplayScore.Start () (at Assets/Scripts/DisplayScore.cs:23)
     
  3. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    7,458
    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.
     
  4. timtbruyn

    timtbruyn

    Joined:
    Dec 17, 2019
    Posts:
    3
    Thanks, you were right! Turned out I had the same script on another object that I forgot about.
     
    Joe-Censored likes this.
unityunity