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

上一篇:对象的生命周期


下一篇:chmod(): Operation not permitted