ProjectDDD/Packages/SLUnity/SLSceneController.cs
2025-07-08 19:46:31 +09:00

160 lines
3.7 KiB
C#

using Superlazy;
using System.Collections;
using UnityEngine;
using UnityEngine.ResourceManagement.ResourceProviders;
using UnityEngine.SceneManagement;
public class SLSceneController : MonoBehaviour
{
public static void Init()
{
inst = new GameObject("SceneController").AddComponent<SLSceneController>();
}
public static bool Loaded { get; private set; } = true;
private static SLSceneController inst;
private SceneInstance oldScene;
private SceneInstance currentScene;
private bool setupEnd = false;
private bool activeEnd = false;
private string scene = "";
public static void ChangeScene(string newScene) // 구버전 하위 호환성
{
inst.SetupAndChange(newScene);
}
public static void SetupScene(string newScene)
{
inst.Setup(newScene);
}
public static void ChangeScene()
{
inst.Change();
}
private void Setup(string newScene)
{
if (newScene == scene)
{
return;
}
if (Loaded == false)
{
SLLog.Error($"Already Load [{scene}] Can't Load [{newScene}]");
return;
}
scene = newScene;
Loaded = false;
setupEnd = false;
activeEnd = false;
oldScene = currentScene;
currentScene = default;
if (string.IsNullOrEmpty(newScene) == false)
{
var handler = SLResources.LoadScene(newScene, LoadSceneMode.Additive);
handler.Completed += (op) =>
{
currentScene = op.Result;
foreach (var rootObj in currentScene.Scene.GetRootGameObjects())
{
rootObj.SetActive(false);
}
setupEnd = true;
};
}
else
{
setupEnd = true;
}
}
private void Change()
{
StartCoroutine(ChangeSceneCoroutine());
}
private IEnumerator ChangeSceneCoroutine()
{
yield return new WaitUntil(() => setupEnd);
if (oldScene.Scene.IsValid())
{
var deactiveHandler = SLResources.UnloadScene(oldScene);
deactiveHandler.Completed += (op) =>
{
oldScene = default;
};
}
if (currentScene.Scene.IsValid())
{
var activeHandler = currentScene.ActivateAsync();
activeHandler.completed += (op) =>
{
foreach (var rootObj in currentScene.Scene.GetRootGameObjects())
{
rootObj.SetActive(true);
}
activeEnd = true;
};
}
else
{
//activeEnd = true;
}
yield return new WaitUntil(() => oldScene.Scene.IsValid() == false && activeEnd);
LightProbes.Tetrahedralize();
Loaded = true;
}
private void SetupAndChange(string newScene)
{
if (newScene == scene)
{
return;
}
if (Loaded == false)
{
SLLog.Error($"Already Load [{scene}] Can't Load [{newScene}]");
return;
}
StartCoroutine(ChangeRoutine(newScene));
}
private IEnumerator ChangeRoutine(string newScene)
{
Loaded = false;
if (string.IsNullOrEmpty(scene) == false)
{
yield return SLResources.UnloadScene(currentScene);
}
scene = newScene;
if (string.IsNullOrEmpty(scene) == false)
{
var handler = SLResources.LoadScene(scene, LoadSceneMode.Additive, true);
yield return handler;
currentScene = handler.Result;
}
LightProbes.Tetrahedralize();
Loaded = true;
}
}