13 private class SceneMapping
15 public string ScenePath =
string.Empty;
17 [Tooltip(
"This toggle enables or disables the generation of a button for this specific scene.")]
18 public bool IsButtonEnabled =
false;
22 [Tooltip(
"The button scene mapping to keep track of which scenes are enabled in the scene launcher. This list of scenes is generated from the build window's active scenes.")]
23 private SceneMapping[] sceneMapping = null;
25 [Tooltip(
"Location of the center of the grid of buttons in Unity space.")]
26 public GameObject ButtonSpawnLocation = null;
28 [Tooltip(
"Prefab used as a button for each scene.")]
31 [Tooltip(
"Number of rows in the grid of buttons. As more scenes are added, they will spread out horizontally using this number of rows.")]
32 public int MaxRows = 5;
34 private int SceneLauncherBuildIndex {
get;
set; }
35 private Vector3 sceneButtonSize = Vector3.one;
37 private void OnValidate()
39 Debug.Assert(SceneButtonPrefab != null,
"SceneLauncher.SceneButtonPrefab is not set.");
58 if (SceneButtonPrefab == null)
63 SceneLauncherBuildIndex = SceneManager.GetActiveScene().buildIndex;
67 var sceneButtonForSizeCollider = sceneButtonForSize.GetComponent<Collider>();
69 if (sceneButtonForSizeCollider != null)
71 sceneButtonSize = sceneButtonForSizeCollider.bounds.size;
74 for (
int sceneIndex = 0; sceneIndex < sceneMapping.Length; ++sceneIndex)
76 if (sceneMapping[sceneIndex].IsButtonEnabled)
78 CreateSceneButton(ButtonSpawnLocation, sceneIndex);
82 Destroy(sceneButtonForSize.gameObject);
85 private void CreateSceneButton(GameObject buttonParent,
int sceneIndex)
87 string sceneName = sceneMapping[sceneIndex].ScenePath;
88 sceneName = sceneName.Substring(sceneName.LastIndexOf(
"/", StringComparison.Ordinal) + 1);
89 sceneName = sceneName.Replace(
".unity",
"");
90 var scene = SceneManager.GetSceneByBuildIndex(sceneIndex);
91 Debug.Assert(SceneManager.GetSceneByName(sceneName) == scene);
93 SceneLauncherButton sceneButton = Instantiate(SceneButtonPrefab, GetButtonPosition(sceneIndex, sceneMapping.Length), Quaternion.identity, buttonParent.transform);
99 private Vector3 GetButtonPosition(
int sceneIndex,
int numberOfScenes)
101 int yCount = Mathf.Min(numberOfScenes, MaxRows);
102 int xCount = (numberOfScenes - 1) / yCount + 1;
103 int x = sceneIndex % xCount;
104 int y = sceneIndex / xCount;
105 Debug.Assert(x < xCount && y < yCount);
109 var topLeft =
new Vector3((xCount - 1) * -0.5f, (yCount - 1) * 0.5f, 0.0f);
110 var cellFromTopLeft =
new Vector3(x, -y, 0.0f);
112 var positionOffset = Vector3.Scale(topLeft + cellFromTopLeft,
new Vector3(sceneButtonSize.x, sceneButtonSize.y, 1.0f));
114 return ButtonSpawnLocation.transform.position + positionOffset;
119 Debug.LogFormat(
"SceneLauncher: Returning to SceneLauncher scene {0}.", SceneLauncherBuildIndex);
120 SceneManager.LoadSceneAsync(SceneLauncherBuildIndex, LoadSceneMode.Single);
121 ButtonSpawnLocation.SetActive(
true);