NGUI的异步场景加载进度条

1、直接创建三个场景,其中第二个场景是用来显示进度条加载的界面,进度条用UISlider

2、这里提供两种方法,建议使用第一种,加载比较平缓

方法一:

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

public class LoadingPags : MonoBehaviour
{


    public UISlider progressBar;            //进度条的引用                 
    private string ScenceName="C";       //加载场景的名字
    private  float dtimer = 0;
    private  float target = 0;

    AsyncOperation op = null;

    private void Start()
    {
        Debug.Log("进入异步");


        //op = SceneManager.LoadSceneAsync(ScenceName);          //进入loadScene方法
        //op.allowSceneActivation = false;

        progressBar.value = 0;                                      //弃用前将其进行初始化了
        StartCoroutine(ProcessLoading());
    }


    private void Update()
    {
        dtimer += Time.deltaTime;
        progressBar.value = Mathf.Lerp(progressBar.value, target, dtimer * 0.2f);          
        //乘以的数值用来控制加载的速度,当新场景比较小的时候可以使用较小的值,有一定的效果,当场景加载较大的时候就不建议这么使用了
        if(progressBar.value>=0.99f)
        {
            progressBar.value = 1;                          //使其的值达到完整
            op.allowSceneActivation = true;             //为true 的时候才可以进行加载新的场景
        }
       
    }
    IEnumerator ProcessLoading()
    {

        op = SceneManager.LoadSceneAsync(ScenceName);          //进入loadScene方法
        op.allowSceneActivation = false;

        while (true)                        //死循环,使其在场景没有加载完成时就不退出了
        {
            target = op.progress;
            if(target>=0.9f)                //当场景加载了90%了
            {
                target = 1;
                yield break;
            }
            yield return 0;

        }
    }
}

第二种:

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

public class Loadign : MonoBehaviour {

    public UISlider uislider;
    private AsyncOperation asyn=null;

    public static string LoadingName;           //声明一个静态的字符串变量俩保存要加载的场景名称
    void Start ()
    {
        if(uislider)
        {
            //进度条丢失了
        }
        StartCoroutine(Loading());
    }
    
    // Update is called once per frame
    void Update ()
    {

        uislider.value = asyn.progress;
        //Debug.Log(uislider.value);
        //if (uislider.value>=0.8)
        //{
        //    uislider.value = 1;

        //    asyn.allowSceneActivation = true;
        //}

    }
    IEnumerator Loading()
    {
        asyn = SceneManager.LoadSceneAsync(2);          //加载第三个尝尽
        asyn.allowSceneActivation = false;
        //uislider.value = asyn.progress;         //赋值
        yield return asyn;
    }

    //封装好的静态函数
    public static void LoadNewScene(string value)
    {
        LoadingName = value;
        SceneManager.LoadScene("Loadign");
    }

}

 

posted @ 2018-03-29 23:59  Turtle_Zhang  阅读(251)  评论(0编辑  收藏  举报