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?