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

  1. 创建两个场景:现在的场景“NowScene”,要加载的场景“LoadScene”;
  2. “NowScene”如图所示,“LoadScene”任意;
  3. 创建脚本“AsyncLoadScene”,复制如下代码,挂在到Canvas上;
  4. 推拽"Slider"和"Text"到面板上;
  5. 注意将要加载的场景添加到《Scenes In Build》,否则加载时回报空引用。
复制代码
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class AsyncLoadScene : MonoBehaviour
{
    // 进度条
    public Slider loadingSlider;
    // 文字显示加载进度
    public Text loadingText;
    // 进度条的行进速度
    private float SliderLoadSpeed = 1;
    // 场景加载类的对象
    private AsyncOperation operation;
    // 加载进度(由于加载进度不能为 1,所以需要此变量在加载进度大于某一个值时让加载进度变为1)
    private float targetValue;

    void Start ()
    {
        // 初始化进度条
        loadingSlider.value = 0.0f;

        if (SceneManager.GetActiveScene ().name == "NowSence") {
            // 启动协程
            StartCoroutine (AsyncLoading ());
        }
    }

    void Update ()
    {
        // operation.progress 加载进度
        targetValue = operation.progress;

        if (operation.progress >= 0.9f) {
            // operation.progress的值最大为0.9
            targetValue = 1.0f;
        }

        if (targetValue != loadingSlider.value) {
            // 插值运算(进度条向当前加载进度趋近)
            loadingSlider.value = Mathf.Lerp (loadingSlider.value, targetValue, Time.deltaTime * SliderLoadSpeed);
            // 避免插值运算一直进行
            if (Mathf.Abs (loadingSlider.value - targetValue) < 0.01f) {
                loadingSlider.value = targetValue;
            }
        }
        // 显示加载百分比
        loadingText.text = ((int)(loadingSlider.value * 100)).ToString () + "%";

        // 当进度条完成 100% 时,加载场景
        if ((int)(loadingSlider.value * 100) == 100) {
            //允许异步加载完毕后自动切换场景
            operation.allowSceneActivation = true;
        }
    }

    // 加载场景的协程
    IEnumerator AsyncLoading ()
    {
        // 异步加载场景
        operation = SceneManager.LoadSceneAsync ("LoadSence");
        // 阻止当加载完成自动切换
        operation.allowSceneActivation = false;

        yield return operation;
    }

}
复制代码

 

posted on   考拉宝贝  阅读(3695)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示