Debug

Hi guys,

I have a little problem with a script

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

you need to cast currentHealth/maxHealth because an int divide by another int by default give you a int (in this case 0)

healthBarLength = (Screen.width / 2) * (currentHealth /(float)maxHealth);

Hi there, you devide two integers, the result of an integer devision is always an integer too, the floating point part is cut away:

1/3 = 0
1/2 = 0
eg.

you need to cast at least one of the both numerals to a floating point value:

(float)currentHealth / maxHealth

should do the trick.

You need to cast the Result of the division to float.
Since integers do not support floating numbers (not sure if that is the right name in english)

Example:

private var maxHealth:int =100;
private var currentHealth:int =80;

Debug.Log((int)currentHealth / maxHealth);   // 80 / 100 = 0    
Debug.Log((float)currentHealth / maxHealth); // 80 / 100 = 0.8

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 :wink:

The code posted is Unityscript, which doesn’t have the (float) casting syntax. Use parseFloat instead.

–Eric

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.

Thanks all!!

It works!!!