Optimization with math

How can I optimize this code with math?

I have 50 sprites that it needs to switch between and I don’t really want to use 50 if statements

private void ManageBars()
{
    if(playerController.Health <= 100 && playerController.Health > 98)
    {
        HealthBar.sprite = HealthBarSprites[0];
    }

    if(playerController.Health <= 98 && playerController.Health > 96)
    {
        HealthBar.sprite = HealthBarSprites[1];
    }

    if(playerController.Health <= 96 && playerController.Health > 94)
    {
        HealthBar.sprite = HealthBarSprites[2];
    }

    if(playerController.Health <= 94 && playerController.Health > 92)
    {
        HealthBar.sprite = HealthBarSprites[3];
    }
}

Thank you!

Math is the language of describing patterns, so if a pattern exists then it can indeed be described with math.

To find the array index, the patterns I note from your code is:

  1. Index is inversely proportional to health:

    100f - health

  2. Index increments by health in steps of 2:

    (100f - health) / 2f

  3. Index must be an integer, rounded down to the nearest whole number:

    Mathf.FloorToInt((100f - health) / 2f)

For example this:

if (playerController.Health <= 94 && playerController.Health > 92)
{
       HealthBar.sprite = HealthBarSprites[3];
}

Is this:

100 - 94 = 6, 6 / 2 = 3

and

100 - 93 = 7, 7 / 2 = 3.5, which floored = 3

We now have an algorithm that satisfies each of your conditions:

int index = Mathf.FloorToInt((100f - health) / 2f);
HealthBar.sprite = HealthBarSprites[index];