Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Health bar won't re-fill

2040Damian2040Damian Member
edited August 2020 in Programming

Hey. So I have a health bar (thanks to the brackets tutorial) that decreases when damaged. The issue is it won't re-fill when I pick up a health item (although the inspector shows the health increase).


Here is the code from my health bar script :


public class HealthBar : MonoBehaviour

{

  public Slider slider;

  public Gradient gradient;

  public Image fill;


   


  public void SetMaxHealth(int health)

  {

    slider.maxValue = health;

    slider.value = health;


    fill.color = gradient.Evaluate(1f);

  }


  public void SetHealth(int health)

  {

    slider.value = health;

    fill.color = gradient.Evaluate(slider.normalizedValue);

  }



}


Here is the code from my health item script:


public class HealthItem : MonoBehaviour

{

  PlayerHealth playerHealth;

   

   

  public int healthBonus = 15;

  private void Awake()

  {

    playerHealth = FindObjectOfType<PlayerHealth>();


  }


  private void OnTriggerEnter2D(Collider2D collision)

  {

    if(playerHealth.currentHealth < playerHealth.maxHealth)

    {

      Destroy(gameObject);

      playerHealth.currentHealth = playerHealth.currentHealth + healthBonus;


       

    }

    else

    {

      Destroy(gameObject);

    }

  }


}


Here is the code from my player health script:


public class PlayerHealth : MonoBehaviour

{

  public Animator animator;

  [SerializeField] Transform spawnPoint;

  public int maxHealth = 100;

  public int currentHealth;


  public HealthBar healthbar;


  // Start is called before the first frame update

  void Start()

  {

    currentHealth = maxHealth;

    healthbar.SetMaxHealth(maxHealth);

  }


  // Update is called once per frame

  void Update()

  {

     

  }


  public void TakeDamage(int damage)

  {

    currentHealth -= damage;

    healthbar.SetHealth(currentHealth);

    animator.SetTrigger("Hurt");


    if (currentHealth <= 0)

    {

      // play hurt animation

      Die();


    }

  }


  void Die()

  {

    animator.SetTrigger("IsDead");

    Invoke("ReSpawn", 1f);



  }


  void ReSpawn()

  {


    if (currentHealth <= maxHealth)

    {

      currentHealth = maxHealth;

      healthbar.SetMaxHealth(maxHealth);

    }

    transform.position = spawnPoint.position;

  }

}

Any help is greatly appreciated!!

Best Answer

  • JIMMY_VASHI04JIMMY_VASHI04 Member
    Accepted Answer

    When you set the player's current health you also nees to change thw slider value to visualize it in the scene

Answers

  • You beautiful human! I'd been starring at that code for hours and totally missed that I didn't have anything in the void Update method!

Sign In or Register to comment.