Skip to content

Instantly share code, notes, and snippets.

@aholkner
Last active April 29, 2021 11:58
Show Gist options
  • Save aholkner/fea2b565082d8deecb0c0388c2b530d6 to your computer and use it in GitHub Desktop.
Save aholkner/fea2b565082d8deecb0c0388c2b530d6 to your computer and use it in GitHub Desktop.
Unity editor extension to allow for quick scene switching from menu
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
/// Add a `Scenes` menu to Unity editor for quick access to all scenes in project.
///
/// Generates/updates a `ScenesMenu.cs` file with the required menu annotations.
public static class ScenesMenuBuild
{
// Path on filesystem (relative to Assets directory) to write menu command scripts.
// This can be inside any "Editor" folder.
static readonly string ScenesMenuPath = "Scripts/Editor/ScenesMenu.cs";
[MenuItem("Scenes/Update This List")]
public static void UpdateList()
{
string scenesMenuPath = Path.Combine(Application.dataPath, ScenesMenuPath);
var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("// Generated file");
stringBuilder.AppendLine("using UnityEditor;");
stringBuilder.AppendLine("using UnityEditor.SceneManagement;");
stringBuilder.AppendLine("public static class ScenesMenu");
stringBuilder.AppendLine("{");
foreach (string sceneGuid in AssetDatabase.FindAssets("t:Scene", new string[] { "Assets" }))
{
string sceneFilename = AssetDatabase.GUIDToAssetPath(sceneGuid);
string sceneName = Path.GetFileNameWithoutExtension(sceneFilename);
string methodName = sceneFilename.Replace('/', '_').Replace('\\', '_').Replace('.', '_');
stringBuilder.AppendLine($" [MenuItem(\"Scenes/{sceneName}\", priority = 10)]");
stringBuilder.AppendLine($" public static void {methodName}() {{ ScenesMenuBuild.OpenScene(\"{sceneFilename}\"); }}");
}
stringBuilder.AppendLine("}");
Directory.CreateDirectory(Path.GetDirectoryName(ScenesMenuPath));
File.WriteAllText(scenesMenuPath, stringBuilder.ToString());
Debug.Log($"Updated {scenesMenuPath}");
AssetDatabase.Refresh();
}
public static void OpenScene(string filename)
{
if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
EditorSceneManager.OpenScene(filename);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment