【问题标题】:Problems with a variable defined in a for loop C#在 for 循环 C# 中定义的变量的问题
【发布时间】:2016-10-22 23:21:29
【问题描述】:

我和我的朋友已经破解了几个小时,但我们就是不知道它有什么问题。它本质上是通过一个数组运行的,如果按钮应该被锁定或可交互,如果它为空,它将是可交互的。通过使用播放器首选项,这些设置应在与应用的每个会话中持续存在。

代码如下:

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;

    }
}

目前 unity 显示 5 个错误:

  • 错误 CS1525:意外符号“i”(其中 2 个)
  • 错误 CS1519:类、结构或接口成员声明中出现意外符号“else”
  • 错误 CS1519:类、结构或接口成员声明中出现意外符号“=”
  • 错误 CS8025:解析错误

【问题讨论】:

  • i = 0; 行应该是 int i = 0; 这就是导致符号错误的原因。
  • 微小改进:将“i = i + 1”更改为“i++”

标签: c# arrays loops for-loop


【解决方案1】:

只是猜测,但你应该写:

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

你可能忘记声明i

还有这一行:

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

string.Format 是string 的静态方法。语法错误。你可以这样写:

PlayerPrefs.GetInt("button" + i)

或者这样:

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

【讨论】:

  • 谢谢,这解决了我的问题:D 对不起,我是 C# 新手,所以我还不知道字符串等的所有语法。
  • 没问题! :) 很高兴能帮上忙!
  • 啊,如果对你有帮助,请将此帖子标记为答案:) 点击复选标记
  • ++i 必须是 i++
  • 在 for 循环中没有区别,因为增量是单个操作指令。使用它是有意义的:var value = ++i;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-05
  • 2022-01-18
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
相关资源
最近更新 更多