1. 程式人生 > >Unity 非同步載入 解決方案

Unity 非同步載入 解決方案

遊戲在跳轉大場景介面時,直接切換場景,會產生長時間的卡頓,體驗很不好(還以為遊戲掛掉了)

今天主要研究Unity的非同步載入

新的非同步載入介面 需要名稱空間

using UnityEngine.SceneManagement;

使用

//非同步載入
SceneManager.LoadSceneAsync(loadName,LoadSceneMode.Additive);
SceneManager.LoadSceneAsync(loadName, LoadSceneMode.Single);
//同步載入
SceneManager.LoadScene(loadName, LoadSceneMode.Additive);
SceneManager.LoadScene(loadName, LoadSceneMode.Single);

LoadSceneMode.Additive 累加形勢載入場景,保留之前的場景

LoadSceneMode.Single 載入場景完場景以後,刪除掉之前的場景

我們主要討論非同步載入 -》LoadSceneAsync

using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoadingUI : MonoBehaviour {
    public static string loadName;
    public Text text;
    //非同步物件
    AsyncOperation async;
    int displayProgress = 0;
    int toProgress = 0;
    //讀取場景的進度,它的取值範圍在0 - 1 之間。
    int progress = 0;

    void Start()
    {
        //在這裡開啟一個非同步任務,
        //進入loadScene方法。
        StartCoroutine(loadScene());
    }

    //注意這裡返回值一定是 IEnumerator
    IEnumerator loadScene()
    {
        //非同步讀取場景。
        //Globe.loadName 就是A場景中需要讀取的C場景名稱。
        async = SceneManager.LoadSceneAsync(loadName);
        //防止Unity載入完畢後直接切換場景
        async.allowSceneActivation = false;

        while (async.progress < 0.9f)
        {
            toProgress = (int)async.progress * 100;
            while (displayProgress < toProgress)
            {
                ++displayProgress;
                yield return new WaitForEndOfFrame();
            }
        }

        toProgress = 100;
        while (displayProgress < toProgress)
        {
            ++displayProgress;
          
            yield return new WaitForEndOfFrame();
        }
        //切換場景
        async.allowSceneActivation = true;
    }


    void Update()
    {
        //使用UGUI顯示進度
        text.text = displayProgress.ToString();
    }

}

通過非同步載入  獲取AsyncOperation的progress 屬性可以獲取將要載入的場景進度,由於progress值不穩等(Application.LoadLevelAsync並不是真正的載入,而是每一幀載入一點資源,然後給出progress值)

所有我們通過沒幀去更新累加,讓進度值保持穩定累加。

當達到0.9的時候,progress值不會上升,我們強制更改到100,在每幀更新即可。