Harvey Parker-Acheson Harvey Parker-Acheson - 1 month ago 13
C# Question

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:


  • error CS1525: Unexpected symbol `i' (2 of these)

  • error CS1519: Unexpected symbol `else' in class, struct, or interface member declaration

  • error CS1519: Unexpected symbol `=' in class, struct, or interface member declaration

  • error CS8025: Parsing error


Answer

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