场景的异步加载(按钮按下,开始加载)

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

public class Loading : MonoBehaviour {
    //滑动条
    public Slider LoadingSlider;
    //显示进度文字
    public Text LoadingText;

    private float loadingSpeed = 1;
    private float targetValue;
    //异步操作协同程序
    private AsyncOperation operation;
    private bool isLoading;

	void Start () {
        LoadingSlider.value = 0.0f;
    }
    public void LoadingMain()
    {
        StartCoroutine(AsyncLoading());
        isLoading = true;
    }
    IEnumerator AsyncLoading()
    {
        operation = SceneManager.LoadSceneAsync("main");
        //阻止当前加载完成自动切换
        operation.allowSceneActivation = false;
        yield return operation;
    }
    void Update() {
        if (isLoading)
        {
            targetValue = operation.progress;
            //operation.progress异步操作协同程序完成的程度,最大是1
            if (operation.progress >= 0.9f)
            {
                targetValue = 1.0f;
            }
            if (targetValue != LoadingSlider.value)
            {
                //插值运算
                LoadingSlider.value = Mathf.Lerp(LoadingSlider.value, targetValue, Time.deltaTime * loadingSpeed);
                //绝对值
                if (Mathf.Abs(LoadingSlider.value - targetValue) < 0.01f)
                {
                    LoadingSlider.value = targetValue;
                }
            }
            LoadingText.text = ((int)(LoadingSlider.value * 100)).ToString() + "%";
            if ((int)(LoadingSlider.value * 100) == 100)
            {
                //允许异步加载完毕后自动切换场景
                operation.allowSceneActivation = true;
            }
        }
        
    }
    
}

 

你可能感兴趣的:(Unity3D)