今天讲一个比较常用的必备知识,异步场景加载
关于Unity异步加载场景首先要提到两点
1、Application.LoadLevel加载场景的方式早已被SceneManager.LoadSceneAsync(“你的场景名称”)替代,并且在官方API中有提到使用AsyncOperation来决定操作是否完成
2、 关于AsyncOperation: AsyncOperation的progress(0-1)属性在isDone为false时,最大加载到0.9就会暂停,直到isDone为true时才会继续加载0.9-1.0的这10%,而isDone为true或fasle的标志为是: 当allowSceneActivation = false,isDone为false ,allowSceneActivation = false 的作用是让场景不会在加载完成后自动跳转到下一个场景, 当allowSceneActivation = true,isDone才可以为true,直到progress = 1.0时 isDone = true,这点官方API也有提到,
// - FileName: ResSvc.cs
// - Created: true.
// - CreateTime: 2020/08/07 02:27:19
// - Email: 1670328571@qq.com
// - Region: China WUHAN
// - Description: 资源服务
//==========================
public class ResSvc : MonoBehaviour
{
public static ResSvc Instance = null;
public LoadingWnd loadingWnd;
#region 异步场景加载
private Action prgCB = null;
public void AsyncLoadScene(string sceneName, Action loaded)
{
loadingWnd.SetWndState();
AsyncOperation sceneAsync = SceneManager.LoadSceneAsync(sceneName);
prgCB = () =>
{
float val = sceneAsync.progress;
if (val == 1)
{
if (loaded != null)
{
loaded();
}
prgCB = null;
sceneAsync = null;
UISvc.Instance.gameLoadPanel.gameObject.SetActive(false);
}
};
}
private void Update()
{
if (prgCB != null)
{
prgCB();
}
}
// - FileName: LoadingWnd .cs
// - Created: true.
// - CreateTime: 2020/08/07 02:27:19
// - Email: 1670328571@qq.com
// - Region: China WUHAN
// - Description: 加载面板
//==========================
using UnityEngine;
using UnityEngine.UI;
public class LoadingWnd : ViewRoot
{
public Text txtTips;
public Image imgFG;
public Image imgPoint;
public Text txtPrg;
private float fgWidth;
protected override void InitWnd()
{
base.InitWnd();
fgWidth = imgFG.GetComponent<RectTransform>().sizeDelta.x;
SetText(txtTips, "这是一条游戏Tips");
SetText(txtPrg, "0%");
imgFG.fillAmount = 0;
imgPoint.transform.localPosition = new Vector3(-545f, 0, 0);
}
public void SetProgress(float prg)
{
SetText(txtPrg, (int)(prg * 100) + "%");
imgFG.fillAmount = prg;
float posX = prg * fgWidth - 545;
imgPoint.GetComponent<RectTransform>().anchoredPosition = new Vector2(posX, 0);
}
}
//==========================
// - FileName: AsyncSceneState.cs
// - Created: true.
// - CreateTime: 2020/09/15 00:03:58
// - Email: 1670328571@qq.com
// - Region: China WUHAN
// - Description:
//==========================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AsyncSceneState : MonoBehaviour
{
void Start()
{
ResSvc.Instance = this.GetComponent<ResSvc>();
ResSvc.Instance.AsyncLoadScene("SceneDemo", () =>
{
Debug.Log("业务逻辑处理");
Debug.Log("异步切换场景");
});
}
}