using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; #if UNITY_EDITOR using UnityEditor; // Needed to access SceneAsset in the editor #endif public class LevelManager : MonoBehaviour { // A serializable structure that holds a UI button and its corresponding scene [System.Serializable] public class LevelEntry { public Button levelButton; // UI Button assigned in the inspector #if UNITY_EDITOR public SceneAsset levelScene; // Reference to a .unity file, editable in the Inspector (Editor only) #endif [HideInInspector] public string sceneName; // Runtime scene name used for loading (stored automatically) } // A list of LevelEntry objects that can be filled in the inspector public List levels = new List(); // Called when the GameObject is first initialized (before Start) private void Awake() { #if UNITY_EDITOR // In the editor, we convert SceneAsset references into usable scene names foreach (var entry in levels) { if (entry.levelScene != null) { // Get the full path to the scene asset entry.sceneName = AssetDatabase.GetAssetPath(entry.levelScene); // Extract only the scene name (e.g., "Level1" from "Assets/Scenes/Level1.unity") entry.sceneName = System.IO.Path.GetFileNameWithoutExtension(entry.sceneName); } } #endif // Loop through each level entry and hook up the button to load the correct scene foreach (var entry in levels) { // Check if both the button and scene name are set if (entry.levelButton != null && !string.IsNullOrEmpty(entry.sceneName)) { // Store the scene name locally to avoid closure issues in the lambda string sceneToLoad = entry.sceneName; // Add an onClick listener that loads the correct scene when the button is clicked entry.levelButton.onClick.AddListener(() => LoadLevel(sceneToLoad)); } } } // This method is called when a button is clicked, and loads the given scene by name public void LoadLevel(string sceneName) { SceneManager.LoadScene(sceneName); // Load the scene using Unity’s SceneManager } }