- Home /
Slider value going to 3.911555e-07
Hi there,
I'm using a Slider for my HP and MP bars in a game I'm developing, and I'm using this code:
if (other.gameObject.name == "Enemy" && healthBarSlider.value > 0)
{
healthBarSlider.value -= 0.025f;
hpText.text = "HP: " + System.Math.Round(healthBarSlider.value * 100,0);
DamageTaken();
}
else
{
gm.ReloadLevel();
}
This code makes my player lose 5HP per hit from their max of 100. When it reaches 0 it actually shows as 3.911555e-07 in the inspector, and the level doesn't reload. If I take another hit, then it reloads. Does anyone have any idea why this might be happening or how I can fix it? I've tried setting the damage value to 0.1f and the problem doesn't occur then, it's very strange.
I've also come across another problem, which is that the DamageTaken() function never gets called, despite the code above/below it being run.
Answer by Scribe · Jan 30, 2015 at 12:44 PM
It is caused by floating point error, you could solve it by saving your health and any damage does as integer values e.g.
int maxHealth = 100;
int health = 100;
int dmg = 5;
if (other.gameObject.name == "Enemy" && health > 0){
health -= dmg;
healthBarSlider.value = (float)health/maxHealth;
hpText.text = "HP: " + health;
}else{
gm.ReloadLevel();
}
That is untested but hopefully you get the idea, the problem is that there is no way to represent every decimal value as the real numbers are a continuum, so for every two chosen numbers a, b, a =/= b, there still exists and infinite number of values between them, no matter how arbitrarily close a and b are. As computers only have a finite amount of memory, real valued calculations cannot all be done perfectly, unless you have some nice starting values 0.5 for example can be represented exactly with bytes with the standard representation of a float
Scribe
Or if all that matters is how it's displayed in the hpText object, you could just use $$anonymous$$ath.RoundToInt() ins$$anonymous$$d of plain Round() when setting the text value.
Your answer
Follow this Question
Related Questions
How to make slider function properly after an animation? 2 Answers
Healthpickup isn't working 1 Answer
Hello! I need help at my melee script Unity 2D 1 Answer
Center GUIContent and texture for a GUI.Box 1 Answer
I am trying to take away some health from a slider using a coroutine, but it takes away too much 1 Answer