📅  最后修改于: 2023-12-03 15:36:49.293000             🧑  作者: Mango
在游戏中,场景的冻结/解冻操作会频繁进行,但是不同的场景冻结/解冻操作可能有所不同,因此需要对场景的冻结/解冻操作进行统一管理,增强代码可维护性和可读性。
unity中,可以通过SceneManager.LoadSceneAsync()方法异步加载场景,我们可以根据异步加载场景的过程来实现场景冻结/解冻的操作。
1、定义场景管理类
public class SceneManager : MonoSingleton<SceneManager>
{
Stack<AsyncOperation> asyncOperationStack = new Stack<AsyncOperation>();
// 冻结场景
public async Task FreezeScene()
{
AsyncOperation ao = UnityEngine.SceneManagement.SceneManager.UnloadSceneAsync(UnityEngine.SceneManagement.SceneManager.GetActiveScene());
asyncOperationStack.Push(ao);
while (!ao.isDone)
{
await Task.Yield();
}
}
// 解冻指定场景
public async Task UnfreezeScene(string sceneName)
{
AsyncOperation ao = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);
asyncOperationStack.Push(ao);
while (!ao.isDone)
{
await Task.Yield();
}
}
// 取消异步加载
public void CancelAsyncLoad()
{
if (asyncOperationStack.Count > 0)
{
AsyncOperation ao = asyncOperationStack.Pop();
ao.allowSceneActivation = false;
}
}
// 恢复异步加载
public void ResumeAsyncLoad()
{
if (asyncOperationStack.Count > 0)
{
AsyncOperation ao = asyncOperationStack.Pop();
ao.allowSceneActivation = true;
}
}
}
2、使用场景管理类
场景冻结:
SceneManager.Instance.FreezeScene();
解冻场景:
SceneManager.Instance.UnfreezeScene("SceneName");
取消异步加载:
SceneManager.Instance.CancelAsyncLoad();
恢复异步加载:
SceneManager.Instance.ResumeAsyncLoad();
通过场景管理类,我们可以方便地进行场景冻结/解冻的操作,同时可以增强代码的可读性和可维护性,提高代码开发效率。