53 lines
1.6 KiB
C#

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
public class LevelManager : MonoBehaviour
{
// A serializable structure that holds a UI button and its corresponding scene
[System.Serializable]
public class LevelEntry
{
public Button levelButton;
public string sceneName;
}
// A list of LevelEntry objects that can be filled in the inspector
public List<LevelEntry> levels = new List<LevelEntry>();
private void Awake()
{
// 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;
entry.levelButton.onClick.AddListener(() => OnClickLoadLevel(sceneToLoad));
}
}
}
// This method is called when a button is clicked, and loads the given scene by name
public void OnClickLoadLevel(string sceneName)
{
StartCoroutine(LoadAsyncScene(sceneName));
}
IEnumerator LoadAsyncScene(string sceneName)
{
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneName);
// Wait until the asynchronous scene fully loads
while (!asyncLoad.isDone)
{
yield return null;
}
}
}