Unity场景切换——避免在89%卡顿

Unity LoadSceneAsync异步加载场景的时候,通常会卡在89%,并且在整个加载的过程中易出现加载快慢不一,给用户造成卡顿的假象。偶然在A计划中看到,特此分享给各位。
在这里插入图片描述
代码中的scence指的是上图中红色的id号,也可以为场景的名字。

以下代码,亲测可用,话不多说,直接上代码:

public class Loding : MonoBehaviour
{
    public Image processView;//一张图片,将Image 的Image Type 改为Filled模式即可,参照文末图片。
    private void Start()
    {
        LodeGameMethod();
    }
    public void LodeGameMethod()
    {
        StartCoroutine(StartLoding(2));
    }
 //scence 为场景在
    private IEnumerator StartLoding(int scence)
    {
        //当前加载进度
        int displayProgress = 0;
        //目标加载进度
        int toProgress = 0;
        //开启异步加载
        AsyncOperation op = SceneManager.LoadSceneAsync(scence);
        //在场景为加载到100不允许场景被激活
        op.allowSceneActivation = false;
        while (op.progress<0.9f)
        {
            toProgress = (int)op.progress * 100;
            while (displayProgress< 90)
            {
                ++displayProgress;
                Debug.Log(displayProgress);
                SetLoadingPercentage(displayProgress);
                yield return new WaitForEndOfFrame();
            }
        }
        //Unity通常会加载到89%便会卡顿,此时场景已经加载完毕
        toProgress = 100;
        while (displayProgress<toProgress)
        {
            ++displayProgress;
            SetLoadingPercentage(displayProgress);
            yield return new WaitForEndOfFrame();
        }
        //激活已经加载的场景
        op.allowSceneActivation = true;
    }
    /// <summary>
    /// 试试更新进度条
    /// </summary>
    /// <param name="displayProgress"></param>

    private void SetLoadingPercentage(int displayProgress)
    {
        Debug.LogError(displayProgress / 100);
        processView.fillAmount = (float)displayProgress / 100;
    }
  
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值