Health 0 = Respawn (Script Help)

Hello,

Just started in Unity, and currently stuck on this script. The “Player” already is getting health deducted over time, but when it reaches 0 it doesn’t Respawn, as intended.
Would appreciate any help, thank you!

Script:

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

public class PlayerHealth : MonoBehaviour
{
    [Header("---Player Health Parameters---")]
    public int startHealth;
    public int maxHealth;
    public int minHealth;
    [Header("---Health UI Slider---")]
    public GameObject _healthSlider;
    private Slider healthSlider;


    // Use this for initialization
    void Start()
    {
        healthSlider = _healthSlider.GetComponent<Slider>();
        healthSlider.maxValue = maxHealth;
        healthSlider.minValue = minHealth;
        healthSlider.value = startHealth;
    }
    public void ChangeHealth(int changeAmount)
    {
        healthSlider.value += changeAmount;
        if (healthSlider.value < 0)
        {
            KillPlayer();
        }
        if (healthSlider.value > healthSlider.maxValue)
            healthSlider.value = healthSlider.maxValue;
        if (healthSlider.maxValue < 1)
            healthSlider.value = 1;
    }
    private void KillPlayer()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
        FindObjectOfType<AudioManager>().Play("PlayerDeath");
        }
    }

Looking at your code for ChangeHealth, I do not see what this is doing:

        if (healthSlider.maxValue < 1)
            healthSlider.value = 1;

If this were my code, I would start by putting something like this:

        if (healthSlider.value < 0)
        {
            Debug.Log("Player Killed!");
            KillPlayer();
        }

Set the players healthSlider to -100 or so and run. Look for Player Killed! in the log.
If you see it, move the Debug.Log down to your KillPlayer function and try again.
If you don’t see it, you know that you have a bug that is preventing your healtSlider going below 0.

Sorry this is not more helpful, but that is all I can tell from the code posted here.

1 Like

All good and running.
Thank you!