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

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值