87 lines
2.5 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;
}
[SerializeField]
float fadeDuration = 2f;
[SerializeField]
private GameObject _fadeScreenObj;
private Material _fadeMaterial;
// 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));
}
}
_fadeScreenObj = GameObject.FindWithTag("MainCamera").transform.GetChild(0).gameObject;
Renderer _renderer = _fadeScreenObj?.GetComponent<Renderer>();
_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;
}
}