Unity异步加载场景

       加载场景的功能想必在游戏开发中是十分常见的了。如果想从一个场景过渡到另一个包含资源较多的场景,必然需要等待一段时间,这时候就需要有一个过渡场景来告诉用户当前加载的进度。 本案例使用滑动条和文字来显示加载进度。


using System.Collections;

using UnityEngine;

using UnityEngine.UI;

using UnityEngine.SceneManagement;

public class Loading : MonoBehaviour

{

    AsyncOperation async;    //异步对象

    public string SceneName;

    public Slider loadingSlider;    //显示进度的滑动条

    public Text loadingText;          //显示进度的文本

    private float loadingSpeed = 1;

    private float targetValue;

    void Start()

    {

        loadingSlider.value = 0.0f;

        StartCoroutine("LoadScene");

    }


    IEnumerator LoadScene()

    {

        async = SceneManager.LoadSceneAsync(SceneName);

        //async.allowSceneActivation = false;

        print("Loading:"+ async);

        yield return async;

    }

    void Update()

    {

        if (async == null) return;

        targetValue = async.progress;

        //值最大为0.9

        if (async.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)

            async.allowSceneActivation = true;

    }

}


       需要注意的是:场景加载过程中,可能会出现一些耗时的卡线程的操作(比如从数据库读取大量数据到内存),此时应当将相关代码放进另一线程中执行。主线程和副线程同时进行,在副线程完成之前,如果主线程没事做就一直等待,当副线程运行完毕时,给主线程发出信号,此时再完成场景的加载动画。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。