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,在每帧更新即可。

猜你喜欢

转载自blog.csdn.net/Aa85641826/article/details/81633695
今日推荐