Unity 异步加载场景

思路(需要协程)

  1. 创建AsyncOperation类的变量用来获取下个场景
  2. 将allowSceneActivation设置为false
  3. 在每帧中检测isDone
    1. 没加载好就将progress的值赋值给slider的value,因为progress的值是0-1的所以可以直接赋值给value
    2. 显示百分比直接将progress的值 * 100就可以
  4. 判断是否加载完成如果progress是0.9就代表加载完成了,因为我们上面设置了allowSceneActivation为false所以不会自动跳转需要再将值设置为true才会跳转

属性(AsyncOperation)

方法名

简介

allowSceneActivation自动加载下个场景
isDone是否加载好场景
progress

数值是从0到1  显示加载场景的进程

如果allowSceneActivation是false,则最高到0.9


实例

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

public class LoadManager : MonoBehaviour
{
    public GameObject loadScreen;
    public Slider slider;
    public Text text;

    public void LoadNextLevel()
    {
        StartCoroutine(LoadLevel());
    }

    IEnumerator LoadLevel()
    {
        loadScreen.SetActive(true);

        AsyncOperation operation = SceneManager.LoadSceneAsync(SceneManager.GetActiveScene().buildIndex - 1);
        //  设置下一个场景为false
        operation.allowSceneActivation = false;

        //  判断是否加载好场景
        while (!operation.isDone)
        {
            //  progress数值是从0到1  显示加载场景的进程
            //  如果下一个场景不设置为true会一直到0.9
            slider.value = operation.progress;
            //  显示文本百分比
            text.text = (operation.progress * 100).ToString() + "%";

            if (operation.progress >= 0.9f)
            {
                slider.value = 1f;

                text.text = "Press AnyKey to continue";
                //  按下任意按键显示下一个场景
                if (Input.anyKeyDown)
                {
                    operation.allowSceneActivation = true;
                }
            }
            yield return null;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值