- Home /
The question is answered, right answer was accepted
Health below zero but shows negative numbers
Hi guys!
In my game I have 100 health and different enemies who deal different amounts of damage. The problem is that sometimes my health goes negative which I don't want to have. Probably the problem is that I have an enemy who deals like 50 damage and my current health is 60 so it goes negative. That is the way I tried to fix it (it doesn't do the job):
health -= damage;
currentHealth.text = health.ToString();
if(health < 0)
{
health = 0;
}
if (health == 0)
{
Die();
}
Die is basically setting the gameobject inactive. Any ideas?
I would be very grateful
Kind regards
Answer by Eno-Khaon · Jan 08 at 06:01 PM
I don't see why it wouldn't work. The only problem here is your order of operations:
health -= damage;
if(health < 0)
{
health = 0;
}
currentHealth.text = health.ToString();
if(health <= 0) // safer choice, regardless of setting it above
{
Die();
}
The current health value was being transformed into a string BEFORE being set back to 0 if it was negative. That's why it was a matter of order of operations.