Files
aibis-dream/Assets/Scripts/Game Loop/SceneLoader.cs
T
2025-03-01 16:05:51 +08:00

126 lines
3.6 KiB
C#

using System.Collections;
using AibisDream.Framework;
using AibisDream.Kit;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.SceneManagement;
namespace AibisDream
{
public class SceneLoader : Singleton<SceneLoader>
{
#region 场景转换参数
private BindProperty<string> _currentScene;
private AsyncOperationHandle _loadHandle;
private string _sceneToLoad;
private bool _isLoading;
public override void OnSingletonInit()
{
_currentScene = new BindProperty<string>();
}
private void Start()
{
_currentScene.Register(GameLoopManager.Instance.UpdateCurScene);
}
private void OnDisable()
{
_currentScene.RemoveAll();
}
#endregion
/// <summary>
/// 同步场景转换
/// </summary>
/// <param name="targetScene">目标场景</param>
public void LoadScene(string targetScene)
{
StartCoroutine(LoadSceneAsync(targetScene));
}
/// <summary>
/// 异步场景转换
/// </summary>
/// <param name="targetScene">目标场景</param>
/// <returns></returns>
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 重新开始游戏功能
/// <summary>
/// 重新开始游戏,重新加载当前场景
/// </summary>
public void RestartGame()
{
// 确保场景正在加载或卸载前,先重置相关状态
StartCoroutine(RestartGameCoroutine());
}
private IEnumerator RestartGameCoroutine()
{
if (_isLoading)
{
yield return null;
}
else
{
yield return UnloadSceneAsync(_currentScene.Value);
yield return MainUIController.Instance.FadeInSync(1);
DialogController.Instance.StopDialog();
yield return MainUIController.Instance.TVFadeInSync(1);
MainUIController.Instance.ShowMainUI();
StartMenu.Instance.showStartMenu();
StartMenu.Instance.HideEndMenu();
yield return MainUIController.Instance.FadeOutSync(1);
}
}
#endregion
}
}