Unity 实用技巧之 非手动添场景到BuildSettings

2025-09-25 06:24:03

1、打开Unity,新建一个空工程,具体如下图

Unity 实用技巧之 非手动添场景到BuildSettings

2、在工程中新建一个脚本“RefreshScene”,双击脚本或者右键“Open C# Project”打开脚本,具体如下图

Unity 实用技巧之 非手动添场景到BuildSettings

3、在脚本上编写代码,首先设置场景路径,然后设置菜单栏工具栏,接着获取场景数据,最后把数据赋给Build Settings.scens 即可,具体代码和代码说明如下图

Unity 实用技巧之 非手动添场景到BuildSettings

4、“RefreshScene”脚本具体代码如下:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEditor;

using System.IO;

public class RefreshScene :  Editor {

    //场景的相对地址

    private static readonly string scenePath = "Scenes";

    //在菜单栏显示方法

    [MenuItem("Tool/RefreshScene")]

    static void RefreshAllScene() {

        //与应用路径组合成绝对路径

        string path = Path.Combine (Application.dataPath, scenePath);

        //获取Scenes文件夹下的所有场景

        string[] files = Directory.GetFiles (path, "*.unity", SearchOption.AllDirectories);

        //定义场景数组

        EditorBuildSettingsScene[] scenes = new EditorBuildSettingsScene[files.Length];

        //循环把场景添加到场景数组中

        for (int i = 0; i < files.Length; i++) {

            string scenePath = files [i];

            scenes [i] = new EditorBuildSettingsScene (scenePath, true);

        }

        //把场景数组中的数据正式添加到BuildSettings的场景中

        EditorBuildSettings.scenes = scenes;

    }

}

5、脚本编译正确,回到Unity界面,在工程中创建一个“Scenes’文件夹,然后在添加介个场景做测试,具体如下图

Unity 实用技巧之 非手动添场景到BuildSettings

6、打开BuildSettings查看,现在是没有场景数据,具体如下图

Unity 实用技巧之 非手动添场景到BuildSettings

7、在菜单栏“Tool”-“RefreshScene”,刷新添加场景到BuildSettings,具体如下图

Unity 实用技巧之 非手动添场景到BuildSettings

8、再次回到BuildSettings中查看,现在场景就添加上去了,具体如下图

Unity 实用技巧之 非手动添场景到BuildSettings

9、到此,《Unity 实用技巧之 非手动添场景到BuildSettings》讲解结束,谢谢

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢