- Home /
Need Help Improving If Else statement
I'm trying to think of a way to make it so I can increase / decrease the size of my if/else statement based on the numberOfSprites.
So currently in my example numberOfSprites = 5. But if it were to equal 6 I'd want to add an additional else if for anim.SetFloat("Angle", 5); Or if numberOfSprites = 4 I'd want to reduce the number of else if's and the max angle float would be anim.SetFloat("Angle", 3);
Obviously If/else isn't the way to do this. Is there a way to do something like this?
if(angle < 180 / numberOfSprites)
{
anim.SetFloat("Angle", 0);
}
else if (angle > 180 / numberOfSprites && angle < (180 / numberOfSprites) * 2)
{
anim.SetFloat("Angle", 1);
}
else if(angle > (180 / numberOfSprites) * 2 && angle < (180 / numberOfSprites) * 3)
{
anim.SetFloat("Angle", 2);
}
else if(angle > (180 / numberOfSprites) * 3 && angle < (180 / numberOfSprites) * 4)
{
anim.SetFloat("Angle", 3);
}
else
{
anim.SetFloat("Angle", 4);
}
Answer by metalted · Jun 27, 2019 at 07:24 AM
So because the values increment nicely for every next if statement, this problem is perfect for a for loop:
//Calculate the angle range
float angleRange = 180 / numberOfSprites;
for(int i = 0; i < numberOfSprites; i++)
{
if(angle < angleRange * (i + 1))
{
anim.SetFloat("Angle", i);
break;
}
}
//So in your example there are 5 sprites. Lets take a random angle of 85 degrees.
//The angle range will be 180 / 5 = 36 degrees.
//The loop will run 5 times total.
//First run: is the angle smaller than 36 * (0 + 1) = 36 ? -> No so continue.
//Second run: is the angle smaller than 36 * (1 + 1) = 72 ? -> No so continue.
//Third run: is the angle smaller than 36 * (2 + 1) = 108 > -> Yes, so set it to ["Angle", 2], which is the same as ["Angle", i]
//The value is set so break out of the for loop
So because the length of the loop is depending on the amount of sprites, it is infinitely expandable. I'm not able to test this code right now, but I'm pretty sure it works.
After some thinking, I realized that the code could be much simpler than a for loop by just using simple math:
anim.SetFloat("Angle", Mathf.FloorToInt(angle / (180 / numberOfSprites));
So simple of course! For some reason my brain kept going to the possibility of switch statements.
It may have been an option, but it would mean hard-coding a lot of cases in advance. Ain't nobody got time for that! There might even be a shorter way than this, because all we're doing is check if the value is in a certain range and apply that "range index" to the Angle. The way I usually do it is like this, with a for loop. But there might be other ways or even functions for this. Always something to discover!
Your answer
Follow this Question
Related Questions
Any Ideas on how to solve this? 1 Answer
Prevention of air movement 1 Answer
If...else statement with errors 1 Answer