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;
}
}
}
}