1. 程式人生 > >C# Unity3D Loading場景非同步載入程式碼實現

C# Unity3D Loading場景非同步載入程式碼實現

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//引入名稱空間
using UnityEngine.SceneManagement;
using UnityEngine.UI;

/// <summary>
/// 非同步載入場景管理類
/// </summary>
public class LoadingManager : MonoBehaviour
{
    /// <summary>
    /// 進度條
    /// </summary>
    public Slider progressUI;

    /// <summary>
    /// 百分比描述文字
    /// </summary>
    public Text progressValue;

    /// <summary>
    /// 非同步操作類
    /// </summary>
    private AsyncOperation prog;


    void Start()
    {
        //啟動協同
        StartCoroutine(LoadAsycLevel());
    }

    /// <summary>
    /// 設定進度條值
    /// </summary>
    /// <param name="value"></param>
    private void SetProgressValue(int value)
    {
        progressUI.value = value;
        progressValue.text = "當前載入進度" + value + "%";
    }

    /// <summary>
    /// 非同步載入場景
    /// </summary>
    IEnumerator LoadAsycLevel()
    {
        //非同步載入場景
        prog = SceneManager.LoadSceneAsync("Game");
        //如果載入完成,也不進入場景
        prog.allowSceneActivation = false;  

        //最終的進度
        int toProgress = 0;

        //顯示的進度
        int showProgress = 0;

        //測試了一下,進度最大就是0.9
        while (prog.progress < 0.9f)
        {
            //toProcess具有隨機性
            toProgress = (int)(prog.progress * 100);
            Debug.Log((int)(prog.progress * 100));
            while (showProgress < toProgress)
            {
                showProgress++;
                SetProgressValue(showProgress);
                Debug.Log(string.Format("1-------toProgress={0},showProgress={1}", toProgress, showProgress));
                yield return new WaitForEndOfFrame(); //等待一幀
            }
        }
        //計算0.9---1   其實0.9就是載入好了,我估計真正進入到場景是1  
        toProgress = 100;

        while (showProgress < toProgress)
        {
            showProgress++;
            SetProgressValue(showProgress);
            Debug.Log(string.Format("2-------toProgress={0},showProgress={1}", toProgress, showProgress));
            yield return new WaitForEndOfFrame(); //等待一幀
        }

        prog.allowSceneActivation = true;  //如果載入完成,可以進入場景
    }
}