Unity场景异步加载(进度条)

ABC三个场景,A是开始场景,B是进度条场景,C是目标场景

A场景进入B场景的方法

void Load() 
    {
        Global.ScenesNum = 1;//BuildSettings加载的场景下标
        SceneManager.LoadSceneAsync("LoadScene");//切换到进度条场景
    }

Global.ScenesNum就是BuildSettings的下标
Unity场景异步加载(进度条)_第1张图片
这是B场景代码(进度条场景)

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

public class Global
{
    public static int ScenesNum;PlaySettings加载的场景下标
}
public class ZLX_Slider : MonoBehaviour
{
    public Slider loadingSlider;    //进度条控件
    public Text loadingText;
    private float loadingSpeed = 1;
    private float progressValue;
    private AsyncOperation AsyOper;
    void Start()
    {
        loadingSlider.value = 0;  //初始进度条为0
        if (SceneManager.GetActiveScene().name == "LoadScene")
        {
            //启动协程
            StartCoroutine("AsyncLoadingScenes");
        }
    }

    IEnumerator AsyncLoadingScenes()
    {
        AsyOper = SceneManager.LoadSceneAsync(Global.ScenesNum);
        //阻止当加载完成自动切换
        AsyOper.allowSceneActivation = false;
        yield return AsyOper;
    }
    void Update()
    {
        progressValue = AsyOper.progress;
        if (AsyOper.progress >= 0.9f)
        {
            //AsyOper.progress的值最大为0.9
            progressValue = 1.0f;
        }
        if (progressValue != loadingSlider.value)
        {
            //插值计算
            loadingSlider.value = Mathf.Lerp(loadingSlider.value, progressValue, loadingSpeed * Time.deltaTime);
            if (Mathf.Abs(loadingSlider.value - progressValue) < 0.01f)
            {
                loadingSlider.value = progressValue;
            }
        }
        loadingText.text = ((int)(loadingSlider.value * 100)).ToString() + "%";
        if (loadingSlider.value == 1.0f)
        {
            //允许异步加载完毕后自动切换场景
            AsyOper.allowSceneActivation = true;
        }
    }
}

上边方法执行完,就进入到下标为Global.ScenesNum的C场景
Global.ScenesNum数是 xx ,就进入下标为 xx 的场景

你可能感兴趣的:(加载场景,unity)