Question by
Sam3million · Mar 20, 2018 at 08:28 PM ·
c#imagefill
Health Bar Not Working
I'm trying to make a health bar for a game and my code isn't working. I have a separate script that makes it so the floor takes away 10 health. When I touch the floor, the health bar just goes straight to 0. In the inspector I can see that the health is goes down by 10 but the health bar doesn't. Is it something to do with fill.Amount? Can someone help me and explain why?
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Health : MonoBehaviour
{
public const int maxHealth = 100;
public int currentHealth = maxHealth;
public Image healthBar;
float CalculateHealth()
{
return currentHealth / maxHealth;
}
public void TakeDamage(int amount)
{
currentHealth -= amount;
healthBar.fillAmount = CalculateHealth();
if (currentHealth <= 0)
{
Destroy(gameObject);
currentHealth = 0;
Debug.Log("Dead!");
}
}
}
Comment
Answer by nathanlink169 · Mar 20, 2018 at 09:12 PM
You are dividing an integer by an integer, which will cut off the remaining decimal.
You can read more here.
An alternative could be to typecast to a float like this:
return (float)currentHealth / maxHealth;