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);
        }

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));