Search Unity

HP bar not working?

Discussion in 'Scripting' started by Corva-Nocta, May 30, 2021.

  1. Corva-Nocta

    Corva-Nocta

    Joined:
    Feb 7, 2013
    Posts:
    801
    Hey all, I am trying to get a basic health bar working, and I'm not sure why it's not working. My code seems fine, but I can't find where the bug is.

    Code (csharp):
    1. public int maxHealth;
    2. public int currentHealth;
    3. public Image healthbar;
    4.  
    5. public void TakeDamage(int damage)
    6. {
    7.    current Health -= damage;
    8.  
    9.    UpdateHealthBar();
    10. }
    11.  
    12. public void UpdateHealtgBar()
    13. {
    14.    healthbar.fillAmount = (currentHealth / maxHealth);
    15. }
    Every time I run the code, and put in debuts, the currentHealth / max Health is always 0. Which doesn't make much sense to me.

    Any ideas?
     
  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    currentHealth and maxHealth are both integers, so you are performing an integer division.
    Cast to float to get a float result