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

Unity中如何根据解锁关卡列表激活对应关卡按钮

问题解决:根据解锁关卡激活对应按钮容器

错误原因分析

你的代码问题核心在于数据结构滥用和未初始化引用:

  1. NullReferenceException:levelButtons数组既没在代码里初始化,也没在Unity Inspector中赋值,处于null状态,遍历操作自然报错。
  2. CS0030类型转换错误:levelButtons是List<List<GameObject>>[](数组元素为嵌套列表),但你在foreach循环里将其当作List<GameObject>处理,类型完全不匹配。
  3. CS0022索引错误:levelButtons是一维数组,却使用了二维索引[buttonIndex, 0],属于语法错误。
  4. 过度设计的嵌套结构:你的需求是控制8个按钮容器的显隐,完全不需要嵌套列表+数组的复杂组合,属于冗余设计。

另外你提到“无法对父GameObject执行SetActive(false)”是误解——Unity中父对象的SetActive完全有效,禁用父对象会自动隐藏所有子对象,这正是你需要的功能。

修正后的代码

替换原脚本为以下结构简洁、逻辑清晰的代码:

using System.Collections.Generic;
using UnityEngine;

public class LevelSelectionScript : MonoBehaviour
{
    // 在Inspector中拖入8个buttonLevel1~buttonLevel8容器
    public GameObject[] levelButtonContainers;

    void Start()
    {
        // 先禁用所有关卡按钮容器
        foreach (var container in levelButtonContainers)
        {
            container.SetActive(false);
        }

        // 遍历已解锁关卡,激活对应容器
        foreach (string levelName in GameManager.instance.levelsUnlocked)
        {
            if (levelName.StartsWith("Level "))
            {
                if (int.TryParse(levelName.Substring(6), out int levelNumber))
                {
                    // 确保关卡号在有效范围内
                    if (levelNumber >= 1 && levelNumber <= levelButtonContainers.Length)
                    {
                        int containerIndex = levelNumber - 1;
                        levelButtonContainers[containerIndex].SetActive(true);
                    }
                }
            }
        }
    }
}

Unity操作步骤

  1. 将该脚本挂载到levelPanel对象上。
  2. 选中levelPanel,在Inspector窗口找到Level Selection Script组件。
  3. 将Level Button Containers数组的大小修改为8。
  4. 依次将场景中的buttonLevel1到buttonLevel8拖入数组的8个元素槽中。

额外说明

  • 如果需要单独控制每个容器内的按钮(而非控制整个容器),可将GameObject[]改为List<List<GameObject>>,并在Inspector中手动添加每个容器下的按钮列表,但控制容器整体显隐的方式更高效。
  • 确保GameManager.instance已正确初始化(比如在Awake方法中实现单例逻辑),否则会出现新的NullReferenceException。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:32:47