0

I am developing a simple 2D game with unity, and started getting the error NullReferenceException: Object reference not set to an instance of an object even though the code was previously running fine. The error is related to a script controlling the health bar of the character:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class healthBarScript : MonoBehaviour
{
    public Slider slider;

    void Start()
    {
        slider = GetComponent<Slider>();
        Debug.Log(slider);
    }

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

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

}

Which is called by the player script in the awake() function:

    void Awake()
    {
        spriteRenderer = GetComponent<SpriteRenderer>();
        animator = GetComponent<Animator>();
        healthBar = GameObject.Find("HealthBar").GetComponent<healthBarScript>();
        healthBar.SetMaxHealth(maxHealth);
        currentHealth = maxHealth;
    }

I have determined that the line slider.maxValue = maxHeath; is causing the issue: slider is not found when calling SetMaxHealth even though slider is correctly fetched in the Start() call. The reason for this is that the Awake function of the Player script is called before the Start of the healthbar script. How can I solve this?

Johncowk
  • 342
  • 1
  • 16
  • 1
    My number one thumb rule is: **Use `Awake`** for initializing all your own values and components where you don't rely on anithing else being initilaized yet. **Use `Start`** for initializing anything where you do rely on others having initialized themselves (in `Awake`) first. This covers most of the cases ... if this it not enough you have to start using `event` callbacks ;) – derHugo Mar 25 '21 at 14:47
  • @Igor [`Start`](https://docs.unity3d.com/ScriptReference/MonoBehaviour.Start.html) and [`Awake`](https://docs.unity3d.com/ScriptReference/MonoBehaviour.Awake.html) are called by the Unity message system itself ;) – derHugo Mar 25 '21 at 14:48
  • In your case this means my solution would be convert the `healthBarScript.Start` to `Awake` so it only initializes itself first. And then move the `healthBar.SetMaxHealth(maxHealth);` into `Start` – derHugo Mar 25 '21 at 14:50

0 Answers0