unity异步加载进度条

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class LoadScene : MonoBehaviour {

    private Slider slider;          //滑动条
    int currentProgress; //当前进度
    int targetProgress;  //目标进度
    public Image progressImg;

    private void Start()
    {
        currentProgress = 0;
        targetProgress = 0;
        slider = GameObject.Find("Slider").GetComponent<Slider>();
        StartCoroutine(LoadingScene()); //开启协成
    }


    /// <summary>
    /// 异步加载场景
    /// </summary>
    /// <returns>协成</returns>
    private IEnumerator LoadingScene()
    {
        AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(1); //异步加载1号场景
        asyncOperation.allowSceneActivation = false;                          //不允许场景立即激活//异步进度在 allowSceneActivation= false时,会卡在0.89999的一个值,这里乘以100转整形
        while (asyncOperation.progress < 0.9f)                                //当异步加载小于0.9f的时候
        {
            targetProgress = (int)(asyncOperation.progress * 100); //异步进度在 allowSceneActivation= false时,会卡在0.89999的一个值,这里乘以100转整形
            yield return new UnityEngine.WaitForEndOfFrame();
            while (currentProgress < targetProgress) //当前进度 < 目标进度时
            {
                currentProgress += 20;                            //当前进度不断累加 (Chinar温馨提示,如果场景很小,可以调整这里的值 例如:+=10 +=20,来调节加载速度)
                slider.value = (float)currentProgress / 100; //给UI进度条赋值
                yield return new WaitForEndOfFrame();         //等一帧
            }
        }
        targetProgress = 100; //循环后,当前进度已经为90了,所以需要设置目标进度到100;继续循环
        yield return new WaitForEndOfFrame();
        while (currentProgress < targetProgress) //当前进度 < 目标进度时
        {
            currentProgress += 20;                            //当前进度不断累加 (Chinar温馨提示,如果场景很小,可以调整这里的值 例如:+=10 +=20,来调节加载速度)
            slider.value = (float)currentProgress / 100; //给UI进度条赋值
            yield return new WaitForEndOfFrame();         //等一帧
        }
        asyncOperation.allowSceneActivation = true; //加载完毕,这里激活场景 —— 跳转场景成功
    }


    /// <summary>
    /// 由于需要两次调用,在这里进行简单封装
    /// </summary>
    /// <returns>等一帧</returns>
    private IEnumerator<WaitForEndOfFrame> LoadProgress()
    {
        while (currentProgress < targetProgress) //当前进度 < 目标进度时
        {
            currentProgress+=20;                            //当前进度不断累加 (Chinar温馨提示,如果场景很小,可以调整这里的值 例如:+=10 +=20,来调节加载速度)
            slider.value = (float)currentProgress / 100; //给UI进度条赋值
            yield return new WaitForEndOfFrame();         //等一帧
        }
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值