unity editor下,代码添加指定场景到BuildSetting,并把这个场景作为初始场景
时间: 2024-01-17 09:03:01 浏览: 146
在Unity Editor下,可以通过以下代码实现将指定场景添加到Build Settings并将其作为初始场景:
```csharp
using UnityEditor;
using UnityEngine.SceneManagement;
public class BuildSettingsManager
{
[MenuItem("MyMenu/Add Scene To Build Settings")]
static void AddSceneToBuildSettings()
{
// Get the path of the scene to add
string scenePath = "Assets/Scenes/MyScene.unity";
// Get the current Build Settings
EditorBuildSettingsScene[] buildScenes = EditorBuildSettings.scenes;
// Check if the scene is already in the Build Settings
bool isAlreadyAdded = false;
foreach (EditorBuildSettingsScene buildScene in buildScenes)
{
if (buildScene.path == scenePath)
{
isAlreadyAdded = true;
break;
}
}
// If the scene is not in the Build Settings, add it
if (!isAlreadyAdded)
{
EditorBuildSettingsScene[] newBuildScenes = new EditorBuildSettingsScene[buildScenes.Length + 1];
for (int i = 0; i < buildScenes.Length; i++)
{
newBuildScenes[i] = buildScenes[i];
}
newBuildScenes[newBuildScenes.Length - 1] = new EditorBuildSettingsScene(scenePath, true);
EditorBuildSettings.scenes = newBuildScenes;
}
// Set the added scene as the first scene in the Build Settings
for (int i = 0; i < buildScenes.Length; i++)
{
if (buildScenes[i].path == scenePath)
{
EditorBuildSettings.scenes[i].enabled = true;
EditorBuildSettings.scenes[i].moveToTop = true;
break;
}
}
// Set the added scene as the initial scene
Scene scene = SceneManager.GetSceneByPath(scenePath);
if (scene != null)
{
EditorSceneManager.playModeStartScene = scene;
}
}
}
```
这个脚本添加了一个菜单项"MyMenu/Add Scene To Build Settings",可以通过点击这个菜单项来执行将指定场景添加到Build Settings并将其作为初始场景的操作。
阅读全文