1. 程式人生 > 其它 >Unity 非同步載入場景

Unity 非同步載入場景

技術標籤:Unity

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

public class UIStartLoding : MonoBehaviour {

    public Slider Slider_Loding;

    //public Text loadingText;
    private float loadingSpeed = 5;
    private float targetValue;
    private AsyncOperation operation;

    void Start () {
        Slider_Loding.value = 0.0f;
        LoadScenes("02-Room");
    }

    /// <summary>
    /// 載入場景
    /// </summary>
    /// <param name="loadName"></param>
    public void LoadScenes(string loadName)
    {
        StartCoroutine(AsyncLoading(loadName));
    }

    /// <summary>
    /// 非同步載入場景
    /// </summary>
    /// <param name="loadName"></param>
    /// <returns></returns>
    IEnumerator AsyncLoading(string loadName)
    {
        operation = SceneManager.LoadSceneAsync(loadName);
        //阻止當載入完成自動切換場景
        operation.allowSceneActivation = false; 
        yield return operation;
    }

   
    void Update () {
        targetValue = operation.progress;

        //operation.progress的值最大為0.9
        if (operation.progress >= 0.9f)
        {
            targetValue = 1.0f;
        }
        //如果非同步載入的值,不等於當前的差值進度值
        //說明載入還沒有完成
        if (targetValue != Slider_Loding.value)
        {
            //插值運算(當前的值,目標的值,時間)
            Slider_Loding.value = Mathf.Lerp(Slider_Loding.value, targetValue, Time.deltaTime * loadingSpeed);
            //如果差值很接近,那麼就讓他們相等
            if (Mathf.Abs(Slider_Loding.value - targetValue) < 0.01f)
            {
                Slider_Loding.value = targetValue;
            }
        }
        //loadingText.text = ((int)(loadingSlider.value * 100)).ToString() + "%";   //載入的進度百分比
        
        //如果載入的進度條已經載入完成了
        if ((int)(Slider_Loding.value * 100) == 100)
        {
            //允許非同步載入完畢後自動切換場景
            operation.allowSceneActivation = true;
        }
    }
}

end