- Home /
Health Bar going 0 right away
not sure what I'm missing so got character taking damage and the print statements come up just fine when hit 80-60-40-20-0 (dead) etc but my health bar when I take the first hit it just instantly drops to 0.
heres the code I'm using any help would be amazing.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class DamageScript : MonoBehaviour { public int currentHealth = 100; public int maxHealth = 100; int damage = 20; public Image currentHealthBar; public Text ratioText;
void Start()
{
maxHealth = 100;
currentHealth = maxHealth;
UpdateHealthbar ();
}
public void UpdateHealthbar()
{
int ratio = currentHealth / maxHealth;
currentHealthBar.rectTransform.localScale = new Vector3 (ratio, 1, 1);
ratioText.text = (ratio * 100).ToString ("0") + '%';
}
void OnCollisionEnter (Collision col)
{
if (col.gameObject.tag == "Bullet") {
currentHealth -= damage;
print ("hurt" + currentHealth);
if (currentHealth <= 0)
Destroy (gameObject);
{
UpdateHealthbar ();
} if (col.gameObject.tag == "Enemy") {
currentHealth -= damage;
UpdateHealthbar ();
print ("hurt" + currentHealth);
if (currentHealth <= 0)
Destroy (gameObject);
}
}
} }
Answer by vadithiyan · Sep 22, 2017 at 05:27 AM
@justinkatic Use float for ratio, using an int and dividing will give you integer values rounded to the lower integer number. For example : int ratio = 80/100 will be 0.
public void UpdateHealthbar()
{
float ratio = currentHealth / maxHealth;
currentHealthBar.rectTransform.localScale = new Vector3 (ratio, 1, 1);
ratioText.text = (ratio * 100).ToString ("0") + '%';
}
Change UpdateHealthBar script to this.
thanks make sense still dropping to 0 though after that change :(
nm got it I had to change current heath and max health to float values also thanks your a champion
Your answer
Follow this Question
Related Questions
Health Regen Stop After Damage 1 Answer
Health Code, Damage and Healing 0 Answers
Health below zero but shows negative numbers 1 Answer
Help w/variables 0 Answers
Having a game object deal damage 0 Answers