本文轉至:傾戀你的美? ? ?原文鏈接:https://blog.csdn.net/qq_42462109/article/details/83096135? ? 大家多多支持大佬
1、關于Unity異步加載場景首先要提到兩點
①? Application.LoadLevel加載場景的方式早已被SceneManager.LoadSceneAsync("你的場景名稱")替代,并且在官方API中有提到使用AsyncOperation來決定操作是否完成,如圖:
②? 關于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也有提到,如圖:
前提條件介紹完了,下面開始正式介紹Unity異步加載場景的方法:
步驟:
? ? ? ? ? 1、?假設需要從場景A跳轉到場景B,由于場景B場景較大,如果采用同步加載方式,就會在場景A某一幀處卡頓(看上去就像死機了),什么也不能做,假如玩家的電腦配置較高,很快加載完了跳到B場景了還好,但是碰到還在用奔騰處理器的選手,你要他等多久,誰也不知道,所以我們這時新建一個場景C用于顯示進度條(雖然還是需要等待,但是你最起碼給玩家點心理準備)
? ? ? ? ? 2、場景A,此處只放置一個按鈕用于跳轉場景,如圖:
? ? ? ? ?3、場景B,為了能看到進度條的效果,所以特意加大了場景,如圖:
? ? ? 4、顯示進度條的場景C,如圖:
? ? ? ? ? 5、首先從場景A采用同步加載的方式加載到場景C,由于場景C只有顯示進度條的UI,所以這一步即使玩家電腦配置不高,也可以瞬間加載,所以直接采用同步加載,代碼如下:
//實現PointerClickHandler接口用于監聽UGUI鼠標點擊操作
public class ToLoadingScene : MonoBehaviour, IPointerClickHandler {
? ? [Tooltip("下個場景的名字")]
? ? public string nextSceneName;
? ? public void OnPointerClick(PointerEventData eventData) {
? ? ? ? SceneManager.LoadScene(nextSceneName);
? ? }
}
? ? ? ? ? 6、場景C使用協程異步加載下一個場景,同時將異步加載的進程數值轉換為進度條的形式顯示出來,當加載完成時,根據需求選擇自動跳轉到下一個場景還是手動跳轉(此處我選擇手動跳轉),代碼如下:
//這個腳本我掛在了我用于顯示百分比的Text下
public class LoadAsyncScene : MonoBehaviour {
? ? //顯示進度的文本
? ? private Text progress;
? ? //進度條的數值
? ? private float progressValue;
? ? //進度條
? ? private Slider slider;
? ? [Tooltip("下個場景的名字")]
? ? public string nextSceneName;
? ? private AsyncOperation async = null;
? ? private void Start() {
? ? ? ? progress = GetComponent<Text>();
? ? ? ? slider = FindObjectOfType<Slider>();
? ? ? ? StartCoroutine("LoadScene");
? ? }
? ? IEnumerator LoadScene() {
? ? ? ? async = SceneManager.LoadSceneAsync(nextSceneName);
? ? ? ? async.allowSceneActivation = false;
? ? ? ? while (!async.isDone) {
? ? ? ? ? ? if (async.progress < 0.9f)
? ? ? ? ? ? ? ? progressValue = async.progress;
? ? ? ? ? ? else
? ? ? ? ? ? ? ? progressValue = 1.0f;
? ? ? ? ? ? slider.value = progressValue;
? ? ? ? ? ? progress.text = (int)(slider.value * 100) + " %";
? ? ? ? ? ? if (progressValue >= 0.9) {
? ? ? ? ? ? ? ? progress.text = "按任意鍵繼續";
? ? ? ? ? ? ? ? if (Input.anyKeyDown) {
? ? ? ? ? ? ? ? ? ? async.allowSceneActivation = true;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? yield return null;
? ? ? ? }
? ? }
}
從上面代碼看出,我對于progress在sync.allowSceneActivation = false時只能加載到0.9的解決方案為:當progress加載到0.9時,我們默認場景加載完成,直接讓進度條顯示100%,然后等待剩余10%加載完成,期待未來有別的解決方案。
導出后的結果:不會做動圖,多截幾張吧...??
另外提一嘴,在Unity編輯器模式下是看不出來進度條正常變化的,只有導出項目后才能看到正常進度條
---------------------
作者:傾戀你的美
來源:CSDN
原文:https://blog.csdn.net/qq_42462109/article/details/83096135