You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
88 lines
2.1 KiB
88 lines
2.1 KiB
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.SceneManagement;
|
|
|
|
public class SceneLoader : MonoBehaviour
|
|
{
|
|
public static SceneLoader Instance { get; private set; }
|
|
private void Awake()
|
|
{
|
|
if (Instance == null) Instance = this;
|
|
}
|
|
|
|
[Header("Scenes")]
|
|
[SerializeField] private string debugScene;
|
|
[SerializeField] private GameObject disableTest;
|
|
[SerializeField] private List<string> loadedScenes;
|
|
|
|
[Header("ReadOnly")]
|
|
[SerializeField, ReadOnly] private bool loading;
|
|
|
|
private void UnloadAllScenes()
|
|
{
|
|
foreach (var scene in loadedScenes)
|
|
{
|
|
StartCoroutine(UnloadSceneAsync(scene));
|
|
}
|
|
}
|
|
public void LoadScene(string sceneName, Action onLoad)
|
|
{
|
|
disableTest.SetActive(false);
|
|
if (loading)
|
|
{
|
|
Debug.LogWarning("Scene can't start loading if the other scene not loaded yet.");
|
|
return;
|
|
}
|
|
|
|
UnloadAllScenes();
|
|
StartCoroutine(LoadSceneAsync(sceneName, onLoad));
|
|
}
|
|
|
|
public void LoadScene(string sceneName) => LoadScene(sceneName, null);
|
|
|
|
private IEnumerator LoadSceneAsync(string sceneName, Action onLoad)
|
|
{
|
|
yield return null;
|
|
|
|
AsyncOperation operation = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);
|
|
loading = true;
|
|
|
|
Debug.Log("Scene loading...");
|
|
while (!operation.isDone)
|
|
{
|
|
yield return null;
|
|
}
|
|
|
|
yield return null;
|
|
|
|
loading = false;
|
|
loadedScenes.Add(sceneName);
|
|
onLoad?.Invoke();
|
|
Debug.Log("Scene loaded.");
|
|
}
|
|
|
|
private IEnumerator UnloadSceneAsync(string sceneName)
|
|
{
|
|
yield return null;
|
|
|
|
AsyncOperation operation = SceneManager.UnloadSceneAsync(sceneName);
|
|
|
|
while (!operation.isDone)
|
|
{
|
|
yield return null;
|
|
}
|
|
|
|
loadedScenes.Remove(sceneName);
|
|
}
|
|
|
|
private void Start()
|
|
{
|
|
if (debugScene != "")
|
|
{
|
|
LoadScene(debugScene);
|
|
}
|
|
}
|
|
|
|
}
|
|
|