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.
 
 
 
 

109 lines
2.6 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);
}
}
private void Update()
{
if(Input.GetKeyDown(KeyCode.Keypad1))
{
//SceneManager.UnloadScene("TestPrologue");
LoadScene("School");
}
if (Input.GetKeyDown(KeyCode.Keypad0))
{
//SceneManager.UnloadScene("TestSchool");
LoadScene("Prologue");
}
if (Input.GetKeyDown(KeyCode.Keypad2))
{
//SceneManager.UnloadScene("TestSchool");
LoadScene("TestRoom");
}
}
}