前言:最近研究opencv for unity,运行用例列表时,提示我所选的功能场景没有加载到Build Settings里,我看了下几十个例子,于是想找代码一键添加,一开始参考了站内大佬的代码
指路:Unity 代码动态添加场景到 Build Settings
后来自己在2021.3.20f1c1版本的unity上运行的时候,首先遇到了路径需要用相对路径的报错提示,转为相对路径后运行成功,但是加入的场景全显示为已删除,经查后发现是new EditorBuildSettingsScene的时候设定guid失败,官方源码如下
public EditorBuildSettingsScene(string path, bool enabled)
{
m_path = path.Replace("\\", "/");
m_enabled = enabled;
GUID.TryParse(AssetDatabase.AssetPathToGUID(path), out m_guid);
}
public EditorBuildSettingsScene(GUID guid, bool enabled)
{
m_guid = guid;
m_enabled = enabled;
m_path = AssetDatabase.GUIDToAssetPath(guid.ToString());
}
我使用的是上面的构造方法,但实际跑下来guid赋值失败,于是我在自己写的代码里重新进行赋值(ps:可能用下面那个方法不会有bug?)
下面是我在别人代码基础上进行的补充,希望对你有帮助。
using UnityEngine;
using UnityEditor;
using System.IO;
using System;
public class EditBuildSettings : Editor {
//在菜单栏显示方法
[MenuItem("Tools/EditBuildSettings/AddAllScene")]
// 遍历所有场景
static void AddAllScene() {
//获取Assets文件夹下的所有场景
string[] files = Directory.GetFiles (Application.dataPath, "*.unity", SearchOption.AllDirectories);
//定义场景数组
EditorBuildSettingsScene[] scenes = new EditorBuildSettingsScene[files.Length];
//循环把场景添加到场景数组中
for (int i = 0; i < files.Length; i++) {
string scenePath = files [i];
scenePath = Ab2RePath(scenePath, Directory.GetCurrentDirectory());
Debug.Log(scenePath);
GUID m_guid;
GUID.TryParse(AssetDatabase.AssetPathToGUID(scenePath), out m_guid);
EditorBuildSettingsScene scene = new EditorBuildSettingsScene(scenePath, true);
scene.guid = m_guid;
scenes[i] = scene;
}
//把场景数组中的数据正式添加到BuildSettings的场景中
EditorBuildSettings.scenes = scenes;
}
[MenuItem("Tools/EditBuildSettings/ClearAllScene")]
// 清理当前已添加的场景
static void ClearAllScene() {
EditorBuildSettings.scenes = new EditorBuildSettingsScene[0];
}
[MenuItem("Tools/EditBuildSettings/GetAllSceneInfo")]
// 输出所有已添加的场景信息
static void GetAllSceneInfo() {
for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)
{
Debug.Log("Path:"+EditorBuildSettings.scenes[i].path + "\nguid:"+EditorBuildSettings.scenes[i].guid+"\nenabled:"+EditorBuildSettings.scenes[i].enabled);
}
}
// 绝对路径转相对路径
public static string Ab2RePath(string targetPath, string basePath)
{
const string directorySeparatorChar = "\\";
Uri pathUri = new Uri(targetPath);
if (!basePath.EndsWith(directorySeparatorChar))
{
basePath += directorySeparatorChar;
}
Uri folderUri = new Uri(basePath);
return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString().Replace("/", directorySeparatorChar));
}
}