- 此问题在此处已有答案**:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?(5个答案)
2天前关闭。
所以我试着创造一个关卡系统,有点像《愤怒的小鸟》,在你完成一个关卡后,下一个关卡就会解锁,以此类推。
所以为了得到解锁的所有关卡,我使用了playerPref.GetInt和for循环来使这些按钮可交互。但是我得到了一个索引超出了我的LevelsUnlocked循环的界限错误,我不知道为什么完全不知道为什么会发生这种情况,有什么想法吗?(可能是一些愚蠢的事情,因为我有点菜鸟)。
public class LevelManager : MonoBehaviour
{
int LevelUnlocked;
public Button[] Buttons;
void Start()
{
LevelUnlocked = PlayerPrefs.GetInt("LevelUnlocked", 1);
for(int i = 0; i < Buttons.Length; i++)
{
Buttons[i].interactable = false;
}
for (int i = 0; i < LevelUnlocked; i++)
{
Buttons[i].interactable = true;
}
}
}
1条答案
按热度按时间v2g6jxz61#
如果没有看到确切的错误消息,我不能100%肯定,但是
Index out of bounds
意味着您试图访问一个整数太小或太大的数组。应确保
public Button[] Buttons;
的元素数多于LevelUnlocked
此代码应修复您的问题:
另外,请注意数组从0开始。因此,在
Button[] Buttons = new Button[3];
中,第一个按钮是Buttons[0],第二个按钮是Buttons[1],依此类推。调用Buttons[3]将提供Index out of bounds错误。