【问题标题】:How to check how many scenes are in a build in Unity如何在 Unity 中检查构建中有多少场景
【发布时间】:2020-05-16 20:59:41
【问题描述】:

我正在 Unity 中构建一个包含许多场景(AKA 关卡)的手机游戏,我还打算在游戏生命周期的后期通过更新添加更多关卡。为了解决这个问题,我尝试制作一个自动化脚本,查看 Unity 构建中有多少场景,并基于预制件创建相应的 UI 按钮。

为了清楚起见,我会注意,当我说“Unity Build 中的场景”时,我指的是构建菜单中的场景:

并且已经有了索引号。

这不是很多,但这是我当前的脚本,我在场景中有一个 levelManager:

    private Scene[] levels;

    private void Start()
    {
        /// This is the line I'm requesting help with
        levels = // Some way of getting all the scene's in a project put in an array


        foreach (var item in levels)
        {
            // I will handle the button creation and modification later that will go here
        }

    }

【问题讨论】:

标签: c# unity3d


【解决方案1】:

如前所述,您不必自己创建该变量,而是可以简单地读出SceneManager.sceneCountInBildSettings,然后使用SceneManager.GetSceneByBuildIndex 来迭代并获得所有这些场景

// Adjust this in the Inspector
// Set this to the index of level 1
[SerializeField] private int startIndex = 1;

var sceneCount = SceneManager.sceneCountInBildSettings;
levels = new Scene[sceneCount - startIndex];
for(var i = startIndex; i < sceneCount; i++)
{
    level[i] = SceneManager.GetSceneByBuildIndex(i);
}

或者,您也可以在运行前通过编辑器脚本使用EditorBuildSettings.scenes 来执行此操作,例如

#if UNITY_EDITOR
using UnityEditor;
#endif

...

// Make this field serialized so it gets stored together with the scene
[SerializeField] private Scene[] levels;

#if UNITY_EDITOR
    [ContextMenu(nameof(StoreScenes))]
    private void StoreScenes()
    {
        levels = EditorBuildSettings.scenes;
        EditorUtility.SetDirty(this);    
        EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene());
    }
#endif

您可以在构建之前通过转到组件的检查器运行此方法,打开上下文菜单并点击StoreScenes,它将填充您的数组。 #if UNITY_EDITOR 必须使用 UnityEditor 命名空间包装任何内容,因为它将在构建中被剥离,否则您将获得构建异常。

【讨论】:

  • @JhonPiper 这是真的.. 在我的手机上输入这个;) 现在应该可以工作了
  • 现在可以了,在我将您的答案标记为正确之前再问一个问题。假设我有一个主菜单,我想跳过构建设置中的第一个或前几个 id,有没有办法用这个设置来做到这一点?
  • 只需让 for 循环从 level1 的索引开始 AMD 相应地减小数组大小,例如levels = new Scene[sceneCount - 3]; for(var i = 3; ...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多