Hi,
I am several weeks into my first Game Design Project for School, I have a Health Script that works fine but the currentHealth resets with each new Scene. I have been trying to save the currentHealth by using the DontDestroyOnLoad method but have been unable to get it to run.
How do I modify the following code to keep the currentHealth until the character needs to respawn?
Many thanks.
using UnityEngine;
public class Health : MonoBehaviour
{
[SerializeField] private float startingHealth;
public float currentHealth { get; private set; }
private Animator anim;
private bool dead;
private void Awake()
{
currentHealth = startingHealth;
anim = GetComponent();
}
public void TakeDamage(float _damage) //Player takes damage
{
currentHealth = Mathf.Clamp(currentHealth - _damage, 0, startingHealth); //Player Health is current health minus damage
if (currentHealth > 0) //if player health is greater than zero
{
anim.SetTrigger(“hurt”); //if player takes damage and is still alive play hurt animation
}
else
{
if (!dead) //if not dead
{
anim.SetTrigger(“die”); //if health is zero than play death animation
GetComponent().enabled = false; //Player cannot move if dead
dead = true; // player cannot die twice
}
}
}
public void AddHealth(float _value)
{
currentHealth = Mathf.Clamp(currentHealth + _value, 0, startingHealth); //Player may gain Health current Health plus health bonus
}
public void Respawn() // if player respawns health is reset to starting health, reset animation to idle
{
dead = false;
AddHealth(startingHealth);
anim.ResetTrigger(“die”);
anim.Play(“Idle”);
GetComponent().enabled = true;
}
}