Skip to content

Instantly share code, notes, and snippets.

@MephestoKhaan
Created June 17, 2019 10:11
Show Gist options
  • Save MephestoKhaan/c8d4d1287d15dd3f9056d897a7f3e860 to your computer and use it in GitHub Desktop.
Save MephestoKhaan/c8d4d1287d15dd3f9056d897a7f3e860 to your computer and use it in GitHub Desktop.
This script for Unity will add a menu to change to any scene in the Build Settings. You don't need to add it to any game object, it adds itself!
using UnityEngine;
using UnityEngine.SceneManagement;
public class ScenMenu : MonoBehaviour
{
private void OnGUI()
{
var sceneNames = SceneMenuPlacer.SceneNames;
int width = Screen.width / sceneNames.Length;
for (int i = 0; i < sceneNames.Length; i++)
{
Rect rect = new Rect(i * width, 100, width, 100);
if (GUI.Button(rect, sceneNames[i]))
{
SceneManager.LoadScene(i);
}
}
}
}
public static class SceneMenuPlacer
{
public static string[] SceneNames { get; private set; }
//This gets called only once after the first SceneManager.sceneLoaded
[RuntimeInitializeOnLoadMethod]
public static void Initialize()
{
PopulateSceneNames();
ApplyMenu();
SceneManager.sceneLoaded += SceneLoaded;
}
private static void PopulateSceneNames()
{
SceneNames = new string[SceneManager.sceneCountInBuildSettings];
for (int i = 0; i < SceneNames.Length; i++)
{
SceneNames[i] = System.IO.Path.GetFileNameWithoutExtension(SceneUtility.GetScenePathByBuildIndex(i));
}
}
private static void SceneLoaded(Scene arg0, LoadSceneMode arg1)
{
ApplyMenu();
}
private static void ApplyMenu()
{
if (GameObject.Find("SceneMenu") == null)
{
GameObject sm = new GameObject("SceneMenu");
sm.AddComponent<ScenMenu>();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment