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

Unity中创建Scene数组无法在Inspector显示的解决方法咨询

解决Unity中Scene数组无法在Inspector显示的问题

嘿,我一眼就看到你代码里的关键问题了——你声明的数组类型错了!你写的是SceneManager[] scenes,但SceneManager是Unity用来管理场景加载的工具类,不是单个场景的引用类型,这就是为什么Inspector里看不到这个数组。下面给你一步步的解决办法:

1. 纠正数组类型

首先,你需要把数组类型改成SceneAsset[](更适合在编辑模式下拖拽场景)或者Scene[],但后者在Inspector里显示有局限,更推荐用SceneAsset,因为它能直接在Unity编辑器里拖拽场景文件。

另外,public修饰的变量本来就会在Inspector显示,加上[SerializeField]虽然也可以,但有点多余,除非你想把私有变量暴露出来。

2. 修正后的代码示例

这里给你调整好的代码,还加上了遍历数组生成选关按钮的基础逻辑(假设你有一个按钮预制体,放在Resources或者直接引用):

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class LevelSelector : MonoBehaviour
{
    public static int money;
    // 用SceneAsset数组,能直接在Inspector拖拽场景
    public SceneAsset[] levels;
    // 选关按钮的预制体
    public Button levelButtonPrefab;
    // 用来存放按钮的父物体(比如一个ScrollRect的Content)
    public Transform buttonParent;

    void Start()
    {
        GenerateLevelButtons();
    }

    void GenerateLevelButtons()
    {
        if (levels == null || levels.Length == 0)
        {
            Debug.LogWarning("没有分配关卡场景到数组中!");
            return;
        }

        foreach (var level in levels)
        {
            // 实例化按钮
            Button newButton = Instantiate(levelButtonPrefab, buttonParent);
            // 设置按钮文本为场景名称
            newButton.GetComponentInChildren<Text>().text = level.name;
            // 添加点击事件,加载对应场景
            string scenePath = level.path;
            newButton.onClick.AddListener(() => LoadLevel(scenePath));
        }
    }

    void LoadLevel(string scenePath)
    {
        // 通过场景路径加载,避免名称重复的问题
        SceneManager.LoadScene(scenePath);
        money++;
    }

    // 保留你原来的测试方法
    public void nextscencefirst()
    {
        SceneManager.LoadScene("Level2");
        money++;
    }
}

3. 额外注意事项

  • 如果坚持要用Scene[],你需要在代码里手动初始化或者通过SceneManager.GetAllScenes()在运行时获取,但这种方式没法在编辑模式下手动分配场景,所以不适合你的选关需求。
  • 确保你要拖拽的场景已经添加到Build Settings的Scenes In Build列表里了,否则即使拖拽了也没法正常加载。

这样调整后,你就能在Inspector面板里看到levels数组,直接拖拽你的关卡场景进去,运行时就会自动生成对应选关按钮啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 16:58:14