1
0
Fork 0
LaboratoryProtection/Assets/UnityTest/Common/Scripts/Scene/SceneLoader.cs

123 lines
3.1 KiB
C#
Raw Normal View History

2023-09-12 15:55:51 +08:00
using Cysharp.Threading.Tasks;
using PMaker.DependencyInjection;
using Sirenix.OdinInspector;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.SceneManagement;
public class SceneLoader : SingletonMonobehaviour
{
public LoadSceneMode loadSceneMode;
public AssetReference[] sceneReferences;
public int last = -1;
#if UNITY_EDITOR
[SerializeField]
[ReadOnly]
#endif
private Dictionary<int, AsyncOperationHandle> _cache;
protected override void Awake()
{
base.Awake();
_cache = new Dictionary<int, AsyncOperationHandle>();
}
[Button]
[HideInEditorMode]
public async UniTask LoadScene(int index)
{
var key = last != index;
//var key = true;
if (key == true)
{
IoC.GetSingleton<Loading>().Show();
Canvas.ForceUpdateCanvases();
await UniTask.Delay(100);
}
if (key == true && last != -1)
{
await UnLoadScene(last);
last = -1;
}
if (_cache.TryGetValue(index, out var value))
{
await value;
}
else
{
var handle = sceneReferences[index].LoadSceneAsync(loadSceneMode, true);
_cache[index] = handle;
await handle;
last = index;
}
await UniTask.WaitUntil(() => IoC.GetSingleton<SceneLoadMark>() == true);
if (key == true)
{
UniTask.Create(async () => {
await UniTask.Delay(100);
IoC.GetSingleton<Loading>().Hide();
}).Forget();
}
}
[Button]
[HideInEditorMode]
public async UniTask ResetLoadScene(int index)
{
var key = true;
//var key = true;
if (key == true)
{
IoC.GetSingleton<Loading>().Show();
Canvas.ForceUpdateCanvases();
await UniTask.Delay(100);
}
if (key == true && last != -1)
{
await UnLoadScene(last);
last = -1;
}
if (_cache.TryGetValue(index, out var value))
{
await value;
}
else
{
var handle = sceneReferences[index].LoadSceneAsync(loadSceneMode, true);
_cache[index] = handle;
await handle;
last = index;
}
await UniTask.WaitUntil(() => IoC.GetSingleton<SceneLoadMark>() == true);
if (key == true)
{
UniTask.Create(async () => {
await UniTask.Delay(100);
IoC.GetSingleton<Loading>().Hide();
}).Forget();
}
}
[Button]
[HideInEditorMode]
public async UniTask UnLoadScene(int index)
{
if (IoC.GetSingleton<SceneLoadMark>() == true)
{
IoC.RemoveSingleton<SceneLoadMark>();
}
await sceneReferences[index].UnLoadScene();
//AssetBundle.Unload(true);
_cache.Remove(index);
last = -1;
}
}