Problems with a variable defined in a for loop C#

Me and my friend have been hacking at it for hours but we just can't figure out what's wrong with it. It's essentially running through an array and if the button should be locked or interactable, and if it's null it'll be interactable. By using player prefs these settings should persist through each session with the app.

Here's the code:

for (i = 0; i < buttons.Length; i = i + 1) {

    if (PlayerPrefs.GetInt("button" + string.Format i) == null) {

        PlayerPrefs.SetInt("button" + string.Format i, 1);
    }

    if (PlayerPrefs.GetInt("button" + string.Format i) == 1) {

        button.interactable = true;

    } else {

        button.interactable = false;

    }
}

Currently unity is displaying 5 errors:

Upvotes: 0

Views: 226

Answers (1)

DoubleVoid
DoubleVoid

Reputation: 795

Just a guess, but you should write:

for (int i = 0; i < buttons.Length; ++i) {

You maybe forgot to declare i

Also this line:

PlayerPrefs.GetInt("button" + string.Format i)

string.Format is a static method of string. The syntax is wrong. You can write it this way:

PlayerPrefs.GetInt("button" + i)

Or this way:

PlayerPrefs.GetInt(string.Format("button{0}",i));

Upvotes: 5

Related Questions