Unity—切换场景以及进度条

本文介绍了一个Unity中使用异步方式加载场景的示例代码。通过使用SceneManager的异步加载功能,可以在加载过程中显示进度条,并在加载完成后通过用户输入触发场景的最终激活。

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

public class ChangeSceneLevel : MonoBehaviour
{

private AsyncOperation mAsyncOperation;
private int progress = 0;
private int mCurProgress = 0;

public Text tex;
public Image image;

// Use this for initialization
void Start ()
{
    image.fillAmount = 0;
    StartCoroutine(LoadScene());
}

private IEnumerator LoadScene()
{
    //异步加载场景
    mAsyncOperation = SceneManager.LoadSceneAsync(2);

    // 不允许加载完毕自动切换场景,因为有时候加载太快了就看不到加载进度条UI效果了
    mAsyncOperation.allowSceneActivation = false;

    // mAsyncOperation.progress测试只有0-0.9
    while (!mAsyncOperation.isDone && mAsyncOperation.progress < 1)
    {
        yield return mAsyncOperation;

        //不会调用到该位置
        Debug.Log("Done");
    }
}

// Update is called once per frame
void Update ()
{
    if (mAsyncOperation == null)
    {
        return;
    }
    Debug.Log("u:" + mAsyncOperation.progress + ", " + mAsyncOperation.isDone + ", " + progress + ", " + mCurProgress);
    //进度最多只能无限接近0.9(但是到不了0.9),然后场景激活成功后又会变为0
    //isDone始终为false
    if (mAsyncOperation.progress < 0.899)
    {
        progress = (int)(mAsyncOperation.progress * 100);
    }
    else
    {
        progress = 100;
    }
    if (mCurProgress < progress)
    {
        mCurProgress++;
    }

    image.fillAmount = mCurProgress / 100f;
    tex.text = mCurProgress + "%";

    if (mCurProgress >= 100)
    {
        // 必须等进度条跑到100%才允许切换到下一场景
        if (Input.GetKeyDown(KeyCode.Space))
        {
            //切换场景之后上一个场景的代码就失效了,包括该代码
            mAsyncOperation.allowSceneActivation = true;
        }
    }
}

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值