Tutorial: Add scenes to build in the context menu (Unity)

Recently I was working on a game in Unity, which uses one scene per level. In order to add new scenes to the scene build I wrote a little editor code, that adds a “Add scenes to build” functionality to the project-context menu. With this you can simply select a couple of scenes in your project view and automatically add them to your build. The script also checks if the scenes are already added to the build.

 

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

#if UNITY_EDITOR
using UnityEditor;

[InitializeOnLoad]
public static class AddScenesToBuild
{
		[MenuItem ("Assets/AddScenesToBuild", false, 1)] // Add menu item to project-context menu
		static void Init ()
		{
		int i=0;

				if (Selection.objects.Length > 0) {
						List<EditorBuildSettingsScene> llist = new List<EditorBuildSettingsScene> ();
						foreach (EditorBuildSettingsScene s in EditorBuildSettings.scenes)
								llist.Add (s);

						foreach (Object o in Selection.objects) {
								string[] t = AssetDatabase.GetAssetPath (o).Split ('.');
								if (t [1] == "unity") {
										if (!llist.Exists (x => x.path == AssetDatabase.GetAssetPath (o))) {
												EditorBuildSettingsScene scene = new EditorBuildSettingsScene (AssetDatabase.GetAssetPath (o), true);
												llist.Add (scene);
												i++;
										}
								}
								else
				{

					Debug.Log("AddScenesToBuild: Please select scene files (.unity)");
					return;
				}
						}
						EditorBuildSettings.scenes = llist.ToArray();
						Debug.Log("AddScenesToBuild: " + i + " scenes added to build. " + (Selection.objects.Length -i) + " scenes already exist.");
				}
		}

}
#endif
Posted in Tutorials.