private var healthBarLength:float = 0.0;
private var maxHealth:int =100;
private var currentHealth:int =100;
function Start(){
healthBarLength = Screen.width/2;
}
function Update(){
AdjustCurrentHealth(0);
Debug.Log(currentHealth);
Debug.Log(maxHealth);
Debug.Log(currentHealth/maxHealth);
}
function OnGUI () {
GUI.Box(new Rect(10,10, healthBarLength, 20), currentHealth +"/"+maxHealth);
}
function AdjustCurrentHealth(adj:float){
currentHealth+=adj;
if(currentHealth<0)
currentHealth = 0;
if(currentHealth<1)
currentHealth =1;
if(currentHealth>maxHealth)
currentHealth = maxHealth;
healthBarLength = (Screen.width / 2) * (currentHealth / maxHealth);
}
as I know this should work fine. But whenever the currentHealth is below 100, currentHealth/maxHealth will become 0.
it’s quite weird. I tried to Debug.Log(currentHealth) and Debug.Log(maxHealth) and what it shows is 80 and 100. But if I debug.Log(currentHealth/maxHealth) it equals to 0.
And my health bar will become 0 immidiatly, even the health of this object is above 0.
Can anyone point out my mistake here? I’ve changed here and there for a whole day and never worked
Not sure if I got the casting in unityscript right, but you should get the gist of it.
*edit: thanks Marrrk for pointing out that I casted at the wrong spot.
Not exactly, you need to cast at least one of the terms to float, as the result of an integer devision is an integer, so casting the integer result to float will gain you nothing
Or you could just change maxHealth to float. Since you’re not modifying it in any way, the number won’t have any floating point inaccuracies once set to the 100 int.