u3d场景加载及进度条

异步加载场景以及进度条

1.我自己百度搜到的,用起来不错,记录一下

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


public class Loading : MonoBehaviour
{
    private Slider slider;
    private Text sliderText;
    AsyncOperation async;

    //读取场景的进度,它的取值范围在0 - 1 之间。
   // int progress = 0;

    // Start is called before the first frame update
    void Awake()
    {
        sliderText = transform.Find("Loading/Slider/Text").GetComponent<Text>();
        slider = transform.Find("Loading/Slider").GetComponent<Slider>();
       
    }
    void Start() {
        StartCoroutine(LoadingScene());
    }
   

    //设置滑动条
    private void setProgressValue(int value) {
        slider.value = value*0.01f;
        // Debug.Log("slider.value" + async.progress);
        sliderText.text = value.ToString() + "%";
    }
    private IEnumerator LoadingScene()
    {
        async = SceneManager.LoadSceneAsync(GameManager.Instance.targetScene);  //异步加载场景

        async.allowSceneActivation = false;  //假如加载完成,也不进入场景
        int toProgress = 0;
        int showProgress = 0;
        //测试了一下,进度只有0和0.9,坑,没有中间数
        while (async.progress < 0.9f)
        {

            toProgress = (int)(async.progress * 100);
         //   Debug.Log("toProgress" + toProgress);
            while (showProgress < toProgress )
            {
                showProgress++;
                setProgressValue(showProgress);
                yield return new WaitForEndOfFrame(); //等候一帧
            }
             yield return new WaitForEndOfFrame(); //等候一帧
        }
        //计算0.9---1   其实0.9就是加载好了,我估量真正进入到场景是1  
        toProgress = 100;
        while (showProgress < toProgress)
        {
            showProgress++;
            setProgressValue(showProgress);
            yield return new WaitForEndOfFrame(); //等候一帧
        }
        async.allowSceneActivation = true;  //假如加载完成,能够进入场景
    }
}
    

注意一点,加载大的场景用异步加载SceneManager.LoadSceneAsync,例如场景A到场景B到场景C,场景B是进度条,A先同步加载SceneManager.LoadScene到B,B再异步加载到C,而场景B就是挂上面的脚本。如果A异步加载B,那么B异步加载C,可能会出错,我就遇到过,一直加载不到C场景,并且进度条卡死,电脑死机

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值