Shorten code with FOR loop

So yeah, I want some code shorten with a for loop.

I've tried to use this:

	for(int i = 2; health >= healthToSprite && health <= healthToSprite * i; i++ )
		{
			toDraw++;

		}

		print(toDraw);


but the variable " toDraw" never change from 0.




[CODE TO SHORTEN]

void Update () 
	{
		if(health >= healthToSprite && health <= (healthToSprite * 2))
		{
			toDraw = 1;
		}
		if(health >= (healthToSprite * 2) && health <= (healthToSprite * 3))
		{
			toDraw = 2;
		}
		if(health >= (healthToSprite * 3) && health <= (healthToSprite * 4))
		{
			toDraw = 3;
		}
		if(health >= (healthToSprite * 4) && health <= (healthToSprite * 5))
		{
			toDraw = 4;
		}
		if(health >= (healthToSprite * 5) && health <= (healthToSprite * 6))
		{
			toDraw = 5;
		}
		if(health >= (healthToSprite * 6) && health <= (healthToSprite * 7))
		{
			toDraw = 6;
		}
		if(health >= (healthToSprite * 7) && health <= (healthToSprite * 8))
		{
			toDraw = 7;
		}
		if(health >= (healthToSprite * 8) && health <= (healthToSprite * 9 ))
		{
			toDraw = 8;
		}



		print (toDraw);

	}
  • Jylle

Assuming you can live with ‘<’ rather than ‘<=’ for the second part of each comparison, and assuming ‘health’ and ‘healtToSprite’ are integers, you can shorten your code to:

toDraw = health / healthToSprite;

if ‘health’ and ‘healthToSprite’ are floats, you can do:

toDraw = Mathf.FloorToInt(health / healthToSprite);

Note that if ‘health’ < ‘healthToSprite’, toDraw will be 0. I’m not sure how you are handling values outside of 1 to 8 right now.