Files
FablishRPG/Assets/Scripts/LevelLoader.cs

58 lines
1.8 KiB
C#
Raw Normal View History

using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
using UnityEngine.UI;
/// <summary>
/// A global helper to seamlessly load levels using a dedicated Loading Scene.
/// </summary>
public class LevelLoader : MonoBehaviour
{
// The static variable that remembers where we want to go!
public static string targetSceneName = "";
[Header("Loading UI")]
[Tooltip("The UI Slider used as a visual loading progress bar.")]
public Slider loadingProgressBar;
private void Start()
{
// If this script wakes up and there's a target scene defined, it means
// we are currently sitting in the LoadingScene and should start the heavy lifting!
if (!string.IsNullOrEmpty(targetSceneName))
{
StartCoroutine(LoadSceneAsynchronously(targetSceneName));
}
}
/// <summary>
/// Call this from anywhere in your game to trigger the loading screen and go to a new level!
/// Example: LevelLoader.LoadLevel("HouseInterior");
/// </summary>
public static void LoadLevel(string sceneName)
{
targetSceneName = sceneName;
// Asynchronously load the Loading Scene to prevent the Main Menu from freezing!
SceneManager.LoadSceneAsync("LoadingScene");
}
private IEnumerator LoadSceneAsynchronously(string sceneName)
{
// Start loading the heavy scene in the background
AsyncOperation operation = SceneManager.LoadSceneAsync(sceneName);
// Update the loading bar while the scene is loading
while (!operation.isDone)
{
float progress = Mathf.Clamp01(operation.progress / 0.9f);
if (loadingProgressBar != null)
{
loadingProgressBar.value = progress;
}
yield return null;
}
}
}