You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PlayerPrefs.GetInt实现关卡解锁系统时遇索引越界错误求助

关卡解锁系统索引越界问题排查与解决

我想做一个类似《愤怒的小鸟》的关卡系统,完成一关解锁下一关。用PlayerPrefs.GetInt获取已解锁关卡状态,再通过循环设置关卡按钮的可交互性,但在LevelUnlocked的循环里出现了索引越界错误,求帮忙(我是新手,可能犯了低级错误)。

相关代码:

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;

        }

    }

}

问题原因

LevelUnlocked的数值超过了Buttons数组的长度。比如你只有5个关卡按钮(数组最大索引是4),但PlayerPrefs里存的LevelUnlocked是6,循环到i=5时,Buttons[5]就会触发索引越界。

修复方案

  1. 限制解锁关卡数的最大值
    在获取LevelUnlocked后,用Mathf.Clamp把数值限制在1到Buttons.Length之间,避免循环越界:

    LevelUnlocked = PlayerPrefs.GetInt("LevelUnlocked", 1);
    // 确保解锁数不超过实际关卡按钮数量
    LevelUnlocked = Mathf.Clamp(LevelUnlocked, 1, Buttons.Length);
    
  2. 检查编辑器赋值
    在Unity编辑器里确认Buttons数组已经正确拖入了所有关卡按钮,没有空元素,且数组长度和实际关卡数一致。

  3. 关卡解锁时的防护
    当玩家完成关卡更新LevelUnlocked时,同样限制最大值,防止存的数值超出实际关卡数:

    int currentUnlocked = PlayerPrefs.GetInt("LevelUnlocked", 1);
    int nextLevel = currentUnlocked + 1;
    // totalLevelCount替换成你的总关卡数,也可以直接用Buttons.Length
    nextLevel = Mathf.Clamp(nextLevel, 1, Buttons.Length);
    PlayerPrefs.SetInt("LevelUnlocked", nextLevel);
    PlayerPrefs.Save();
    

内容的提问来源于stack exchange,提问作者amal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 01:05:55