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; public string jumpPoint; } [SerializeField] string jumpPointGrottoEssen; [SerializeField] string jumpPointGrottoKueche; [SerializeField] float fadeDuration = 3f; [SerializeField] GameObject fadeScreenObj; private Material _fadeMaterial; // A list of LevelEntry objects that can be filled in the inspector public List levels = new List(); private void Awake() { // Reset entry level points EntryLevel.GoToGrottoKueche = false; EntryLevel.GoToGrottoEssen = false; // 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)); string goToJumpPoint = entry.jumpPoint; entry.levelButton.onClick.AddListener(() => SetEntryLevel(goToJumpPoint)); } } Renderer _renderer = fadeScreenObj?.GetComponent(); _fadeMaterial = _renderer?.sharedMaterial; } // 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) { yield return StartCoroutine(FadeOut()); AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneName); // Wait until the asynchronous scene fully loads while (!asyncLoad.isDone) { yield return null; } } IEnumerator FadeOut() { fadeScreenObj.SetActive(true); float elapsedTime = 0f; Color color = _fadeMaterial.color; while (elapsedTime < fadeDuration) { elapsedTime += Time.deltaTime; float alpha = Mathf.Lerp(0f, 1f, elapsedTime / fadeDuration); color.a = alpha; _fadeMaterial.color = color; yield return null; } // Ensure the final alpha value is set color.a = 1f; _fadeMaterial.color = color; } public void SetEntryLevel(string entryPoint) { if (string.IsNullOrEmpty(entryPoint)) { return; } if (entryPoint == jumpPointGrottoEssen) { EntryLevel.GoToGrottoEssen = true; return; } if (entryPoint == jumpPointGrottoKueche) { EntryLevel.GoToGrottoKueche = true; return; } } }