I’m trying to implement a checkpoint system in my game, where when a player clicks on the checkpoint, they will have their health refilled to full. However, whenever I try to test that part of the code, it gives me a Null Reference Exception and the HealthSlider becomes null. It’s assigned in the inspector so I don’t know what’s causing this. Every other part of the code seems to be working.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour
{
public int startHealth = 2;
public int currentHealth;
public Slider HealthSlider;
public AudioClip hurtClip;
public AudioClip deathClip;
public Animator anim;
public AudioSource playerAudio;
public PlayerMovement pm;
bool isDead;
bool damaged;
// Start is called before the first frame update
void Awake()
{
anim = GetComponent<Animator>();
playerAudio = GetComponent<AudioSource>();
pm = GetComponent<PlayerMovement>();
currentHealth = startHealth;
}
// Update is called once per frame
void Update()
{
if (damaged)
{
playerAudio.clip = hurtClip;
playerAudio.Play();
damaged = false;
}
HealthSlider.value = currentHealth;
}
public void TakeDamage(int amount)
{
damaged = true;
currentHealth -= amount;
if (currentHealth <= 0 && !isDead)
{
Death();
}
}
void Death()
{
isDead = true;
anim.SetTrigger("Die");
playerAudio.clip = deathClip;
playerAudio.Play();
pm.enabled = false;
}
public void ResetHealth()
{
currentHealth = startHealth;
print(HealthSlider);
HealthSlider.value = currentHealth;
}
}