设计思路:
对于场景切换,个人认为有两个比较关键的要点是,场景加载时的回调,一般和update绑定,常用于场景切换时的进度条。另外一个为场景加载完成后的回调。
关键代码:
SceneLoadManager.cs
因为需要每帧调用,故需要继承MonoBehaviour
public class SceneLoadManager : MonoBehaviour
{
}
切换场景提供两个回调函数,一个为场景加载时的回调函数,每帧调用。另外一个为场景加载完成后的回调函数。
public static void LoadScene(string sceneName, UnityAction<float> onProgress, UnityAction onFinish, LoadSceneMode mode = LoadSceneMode.Single)
{
GameObject sceneLoadManager = GameObject.Find("SceneLoadManager");
if (sceneLoadManager == null)
{
sceneLoadManager = new GameObject("SceneLoadManager");
sceneLoadManager.AddComponent<SceneLoadManager>();
DontDestroyOnLoad(sceneLoadManager);
}
//UIManager.Instance.ClearAllWindows();
_asyncOperation = SceneManager.LoadSceneAsync(sceneName, mode);
_onProgress = onProgress;
_asyncOperation.completed += delegate (AsyncOperation asyncOperation)
{
onFinish();
OnCloseLoadSceneUi();
_asyncOperation = null;
_onProgress = null;
};
}
void Update()
{
if (_asyncOperation != null)
{
if (_onProgress != null)
{
_onProgress(_asyncOperation.progress);
OnOpenLoadSceneUi(_asyncOperation.progress);
}
}
}
在update中调用场景加载的ui,一般是一个背景图加一个进度条。在场景加载完成时关闭。
void Update()
{
if (_asyncOperation != null)
{
if (_onProgress != null)
{
_onProgress(_asyncOperation.progress);
OnOpenLoadSceneUi(_asyncOperation.progress);
}
}
}
private static void OnOpenLoadSceneUi(float progress)
{
if (!UIManager.Instance.CheckIsCurView(UIPanelType.UiLoadScene))
{
UIManager.OpenWindows(UIPanelType.UiLoadScene);
}
UIGameLogin curView = UIManager.Instance.GetCurView() as UIGameLogin;
curView.UpdateView(progress);
}
private static void OnCloseLoadSceneUi()
{
if (!UIManager.Instance.CheckIsCurView(UIPanelType.UiLoadScene))
{
UIManager.CloseWindows();
}
}