using System.Collections; using AibisDream.Framework; using AibisDream.Kit; using AibisDream.FixSystem; using AibisDream.UI; using UnityEngine.AddressableAssets; using UnityEngine.ResourceManagement.AsyncOperations; using UnityEngine.SceneManagement; using DG.Tweening; namespace AibisDream { public class SceneLoader : Singleton { #region 场景转换参数 private AsyncOperationHandle _loadHandle; private string _sceneToLoad; private bool _isLoading; private string _currentSceneName; public string CurrentSceneName => _currentSceneName; public bool IsLoading => _isLoading; public override void OnSingletonInit() { } #endregion /// /// 同步场景转换 /// /// 目标场景 public void LoadScene(string targetScene) { StartCoroutine(LoadSceneAsync(targetScene)); } /// /// 异步场景转换 /// /// 目标场景 /// public IEnumerator LoadSceneAsync(string targetScene) { if (_isLoading) { yield return null; } else { // 场景转换参数 _isLoading = true; UIManager.Instance.ShowPreferredLoading(); _sceneToLoad = targetScene; // 在卸载场景前清理所有系统 if (!string.IsNullOrEmpty(_currentSceneName)) { DOTween.KillAll(); if (FixSystemCenter.SystemDic != null) { FixSystemCenter.SystemDic.Clear(); } // 释放场景级资源(在卸载场景之前) ResourceSystem.ReleaseSceneLoader(); yield return Addressables.UnloadSceneAsync(_loadHandle); } // 显式创建 Scene Loader(在所有业务组件 Start 之前) ResourceSystem.CreateSceneLoader(); _loadHandle = Addressables.LoadSceneAsync(_sceneToLoad, LoadSceneMode.Additive); while (!_loadHandle.IsDone) { UIManager.Instance.SetPreferredLoadingProgress(_loadHandle.PercentComplete); yield return null; } UIManager.Instance.SetPreferredLoadingProgress(1f); // 场景加载完成,通知各系统 EnumEventSystem.Global.Send(EventEnum.SceneLoad, _sceneToLoad); _currentSceneName = _sceneToLoad; UIManager.Instance.HidePreferredLoading(); _isLoading = false; } } public IEnumerator UnloadSceneAsync() { if (_isLoading) { yield return null; } else { _isLoading = true; if (_loadHandle.IsValid()) { DOTween.KillAll(); ResourceSystem.ReleaseSceneLoader(); yield return Addressables.UnloadSceneAsync(_loadHandle); _currentSceneName = null; } _isLoading = false; } } } }