using System; using System.Collections; using AibisDream.Kit; using UnityEngine.AddressableAssets; using UnityEngine.ResourceManagement.AsyncOperations; using UnityEngine.SceneManagement; namespace AibisDream { public class SceneLoader : Singleton { #region 场景转换参数 private string currentScene; private AsyncOperationHandle _loadHandle; private string sceneToLoad; private bool isLoading; #endregion #region 场景切换事件 public event Action LoadSceneEvent; public event Action UnloadSceneEvent; #endregion /// /// 同步场景转换 /// /// 目标场景 public void LoadScene(string targetScene) { StartCoroutine(LoadSceneAsync(targetScene)); } /// /// 异步场景转换 /// /// 目标场景 /// public IEnumerator LoadSceneAsync(string targetScene) { if (isLoading) { yield return null; } else { // 场景转换参数 isLoading = true; sceneToLoad = targetScene; if (currentScene != null) { UnloadSceneEvent?.Invoke(); yield return Addressables.UnloadSceneAsync(_loadHandle); } _loadHandle = Addressables.LoadSceneAsync(sceneToLoad, LoadSceneMode.Additive); yield return _loadHandle; LoadSceneEvent?.Invoke(); currentScene = sceneToLoad; isLoading = false; } } public IEnumerator UnloadSceneAsync(string sceneToUnload) { if (isLoading) { yield return null; } else { isLoading = true; if (currentScene == sceneToUnload) { UnloadSceneEvent?.Invoke(); yield return Addressables.UnloadSceneAsync(_loadHandle, true); currentScene = null; } isLoading = false; } } } }