How to add Scenes to the Build Settings

How to add Scenes to the Build Settings

In this post, I want to show you how you can use a script to add Scenes to the Build Settings automatically.

I’m working on a game that will have dozens of levels and the designers just started designing the first ones. Since it will require a lot of experimentation and tweaking, I’ve created a new scene to list and load all the test scenes they are creating.

This requires not only adding each new scene to this menu but also adding the scenes to the build settings. I’ve decided to automate it to speed up this process:

  • First, I´ve used the method AssetDatabase.FindAssets to get all the test Scenes we have in a specific folder created just for that;

-> I’ve started by using AssetDatabase.LoadAllAssetsAtPath but to no avail. It turns out this returns all the sub Assets of the Asset at the given path. I find the name a little misleading.

  • Since I have other Scenes in the Build Settings that I don’t want to lose, I needed to add the new Scenes without replacing the entire list. So, I’ve used the EditorBuildSettings.scenes to get a list of all the Scenes already in the Build Settings;

  • I only wanted to add the new Scenes, so I used the AssetDatabase.GUIDToAssetPath to get each new Scene path and then checked if it was already listed in the Build Settings;

  • I’ve created a new array of EditorBuildSettingsScene with all the existing scenes in the Build Settings plus the new ones and replaced the current list of scenes.

Check the full script below:

var path = "Assets/_Scenes/Tests/";
// Find Assets of Type Scene in the given path.
var sceneGUIDs = AssetDatabase.FindAssets("t:" + nameof(Scene), new[] { path });

// Get all scenes already added to the Build Settings.
var existingBuildScenes = EditorBuildSettings.scenes;
var buildScenesToAdd = new List<EditorBuildSettingsScene>();

for (int i = 0; i < sceneGUIDs.Length; i++)
{
    // Get the new Scene path.
    var scenePath = AssetDatabase.GUIDToAssetPath(sceneGUIDs[i]);

    // Check if the scene is already added to the Build Settings.
    var existingScene = existingBuildScenes.FirstOrDefault(x => x.path == scenePath);
    if (existingScene != null) { continue; }

    buildScenesToAdd.Add(new EditorBuildSettingsScene(scenePath, true));
}

// Create a new array with the existing scenes plus space for the new ones.
var buildScenes = new EditorBuildSettingsScene[existingBuildScenes.Length + buildScenesToAdd.Count];
Array.Copy(existingBuildScenes, buildScenes, existingBuildScenes.Length);

var startIndex = existingBuildScenes.Length;
for (int i = startIndex; i < startIndex + buildScenesToAdd.Count; i++)
{
        buildScenes[i] = buildScenesToAdd[i - startIndex];
}

// Replace the current list of scenes in the Build Settings.
EditorBuildSettings.scenes = buildScenes;