NLDClient-yudde/ProjectNLD/Assets/Code/Scripts/Gameplay/SubSystems/GameSceneManager.cs

81 lines
2.3 KiB
C#

using System.Collections.Generic;
using System.Linq;
using Cysharp.Threading.Tasks;
using PhxhSDK;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceProviders;
using UnityEngine.SceneManagement;
namespace Gameplay.SubSystems
{
/// <summary>
/// 游戏场景的底层逻辑
/// </summary>
public class GameSceneManager : Singlenton<GameSceneManager>
{
public class SceneHandle
{
public Scene Scene { get; private set; }
public SceneHandle(Scene scene)
{
Scene = scene;
}
public Camera SceneMainCamera => CommonUtils.GetSceneRootComponent<Camera>(Scene);
}
private Dictionary<string, AsyncOperationHandle<SceneInstance>> _sceneOpDic = new();
public async UniTask<SceneHandle> LoadSceneAsync(string scenePath, LoadSceneMode mode = LoadSceneMode.Single)
{
if (string.IsNullOrEmpty(scenePath))
{
DebugUtil.LogError($"ScenePath is null!");
return null;
}
if (mode == LoadSceneMode.Single)
_sceneOpDic.Clear();
if (!_sceneOpDic.TryGetValue(scenePath, out var op))
{
op = Addressables.LoadSceneAsync(scenePath, mode);
_sceneOpDic.Add(scenePath, op);
}
await op.ToUniTask();
return new(op.Result.Scene);
}
public async UniTask UnLoadSceneAsync(string scenePath)
{
if (string.IsNullOrEmpty(scenePath))
{
DebugUtil.LogError($"ScenePath is null!");
return;
}
if (!_sceneOpDic.TryGetValue(scenePath, out var op))
{
Debug.LogError($"该场景没有被加载过 scenePath:{scenePath}");
return;
}
_sceneOpDic.Remove(scenePath);
await Addressables.UnloadSceneAsync(op).ToUniTask();
}
public float GetSceneLoadingProgress(string scenePath)
{
if (_sceneOpDic.TryGetValue(scenePath, out var op))
{
return op.PercentComplete;
}
return 0;
}
}
}