1. 程式人生 > >unity中關於非同步loading場景的載入

unity中關於非同步loading場景的載入

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ExcessiveMenuPanel : MonoBehaviour {
    public Scrollbar loadScrollbar;//場景中的進度條
    public Text loadText;//顯示進度的文字
    // Use this for initialization
    void Start () {
        //這裡傳在buildSetting中的id,或者傳字串,把下面的int改為string
        StartCoroutine(StartLoading_4(2));


    }


    /// <summary>
    /// 載入場景,只能載入在BuildSettings設定的場景,我在做載入AssetBundle載入場景是不行的
    /// </summary>
    /// <param name="scene"></param>
    /// <returns></returns>
    private IEnumerator StartLoading_4(int scene)
    {
        int displayProgress = 0;
        int toProgress = 0;
        AsyncOperation op = Application.LoadLevelAsync(scene);
        op.allowSceneActivation = false;
        while (op.progress < 0.9f)
        {
            toProgress = (int)op.progress * 100;
            while (displayProgress < toProgress)
            {
                ++displayProgress;
                SetLoadingPercentage(displayProgress);
                yield return new WaitForEndOfFrame();
            }
        }


        toProgress = 100;
        while (displayProgress < toProgress)
        {
            ++displayProgress;
            SetLoadingPercentage(displayProgress);
            yield return new WaitForEndOfFrame();
        }
        op.allowSceneActivation = true;
    }
    /// <summary>
    /// 設定進度條和文字
    /// </summary>
    /// <param name="num"></param>
    private void SetLoadingPercentage(float num)
    {
        loadScrollbar.size = num * 0.01f;
        loadText.text = num.ToString() + "%";
    }
}