Bunch of "if" statements

Hey there!
Im a beginner in programming and i want to do my first game, i have one problem…
I dont want to have that many “if” statements.
I know that there should be an easier (shorter) way to do this…
Btw… sorry for my english ;//
My script:

    void CheckTheSkin()
    {
        if (PlayerPrefs.GetInt("currentSkin") == 0)
        {
            GetComponent<SpriteRenderer>().sprite = DefaultSkin;
        }
        if (PlayerPrefs.GetInt("currentSkin") == 1)
        {
            GetComponent<SpriteRenderer>().sprite = PriceSkin1;
        }
        if (PlayerPrefs.GetInt("currentSkin") == 2)
        {
            GetComponent<SpriteRenderer>().sprite = PriceSkin2;
        }
        if (PlayerPrefs.GetInt("currentSkin") == 3)
        {
            GetComponent<SpriteRenderer>().sprite = PriceSkin3;
        }
        if (PlayerPrefs.GetInt("currentSkin") == 4)
        {
            GetComponent<SpriteRenderer>().sprite = PriceSkin4;
        }
        if (PlayerPrefs.GetInt("currentSkin") == 5)
        {
            GetComponent<SpriteRenderer>().sprite = PriceSkin5;
        }
    }

Yes, put all your skins in an array. Then use the int as an index.

public sprite[] skinSprites; //assign by inspector or populate it somewhere

void CheckTheSkin(int skinIndex)
{
   GetComponent<SpriteRenderer>().sprite = skinSprites[skinIndex];
}

//Or playerpref version
void CheckTheSkin()
{
   GetComponent<SpriteRenderer>().sprite = skinSprites[PlayerPrefs.GetInt("currentSkin")];
}

I’ll try that. Thank you!

Also, just as a future reference. Try to use switch statements when you can instead of multiple ifs. Or, if you use multiple ifs as you have it, use

if
else if
else

Instead. As you have it, each if statement gets checked. A switch or else if scenario will stop checking values once it finds the matching condition. However, the array method will work better in this case. (this is just advice to keep in mind)

2 Likes