using System.Collections; using AibisDream.Framework; using AibisDream.Kit; using UnityEditor; using UnityEngine.AddressableAssets; using UnityEngine.ResourceManagement.AsyncOperations; using UnityEngine.SceneManagement; namespace AibisDream { public class SceneLoader : Singleton { #region 场景转换参数 private BindProperty _currentScene; private AsyncOperationHandle _loadHandle; private string _sceneToLoad; private bool _isLoading; public override void OnSingletonInit() { _currentScene = new BindProperty(); } private void Start() { _currentScene.Register(GameLoopManager.Instance.UpdateCurScene); } private void OnDisable() { _currentScene.RemoveAll(); } #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 (!string.IsNullOrEmpty(_currentScene.Value)) { yield return Addressables.UnloadSceneAsync(_loadHandle); } _loadHandle = Addressables.LoadSceneAsync(_sceneToLoad, LoadSceneMode.Additive); yield return _loadHandle; _currentScene.Value = _sceneToLoad; _isLoading = false; } } public IEnumerator UnloadSceneAsync(string sceneToUnload) { if (_isLoading) { yield return null; } else { _isLoading = true; if (_currentScene.Value == sceneToUnload) { yield return Addressables.UnloadSceneAsync(_loadHandle); _currentScene.Value = null; } _isLoading = false; } } #region 重新开始游戏功能 /// /// 重新开始游戏,重新加载当前场景 /// public void RestartGame() { // 确保场景正在加载或卸载前,先重置相关状态 StartCoroutine(RestartGameCoroutine()); } private IEnumerator RestartGameCoroutine() { if (_isLoading) { yield return null; } else { // 清除当前场景的状态(如果需要) _isLoading = true; if (!string.IsNullOrEmpty(_currentScene.Value)) { // 卸载当前场景 yield return Addressables.UnloadSceneAsync(_loadHandle); } yield return MainUIController.Instance.FadeInSync(1); DialogController.Instance.StopDialog(); yield return MainUIController.Instance.TVFadeInSync(1); MainUIController.Instance.ShowMainUI(); StartMenu.Instance.showStartMenu(); yield return MainUIController.Instance.FadeOutSync(1); } } #endregion } }