u3d 异步加载场景以及进度条的显示

1、先建立两个场景 

2、把两个场景在在build setting 中添加两个建好的两个场景

3、在第一个场景中建立一个button和slider组件

4、代码处理

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class ButtonTest : MonoBehaviour {

public Button ButtonTestTran;
private AsyncOperation async;
private Slider slider;
void Start () {

ButtonTestTran = transform.Find("Button").GetComponent<Button>();
slider = transform.Find("Slider").GetComponent<Slider>();
ButtonTestTran.onClick.AddListener(()=> {
StartCoroutine(startGame()); //启动协程
});
}
private void ShowSlider(float num,float num2)
{

slider.value = num/ num2;
}
IEnumerator startGame()
{
async = SceneManager.LoadSceneAsync("addScenes1", LoadSceneMode.Single);//异步加载场景
async.allowSceneActivation = false;//async.progress的值增加到0.9后就保持不变 先不跳转场景
int num =0;
int num2 = 0;
while (async.progress < 0.9f)
{
num2 = (int)(async.progress * 100);
while (num < num2)
{
++num;
ShowSlider(num, 100);

yield return new WaitForEndOfFrame();
}
}
num2 = 98;//设置真实的进度为98%
int TempValue = (num2 - num) / 10;
Debug.LogError("num2=" + num2);
Debug.LogError("num=" + num);
Debug.LogError("TempValue=" + TempValue);
TempValue = TempValue == 0 ? 1 : TempValue;
while (num < num2)
{
num += TempValue;
num = num > num2 ? num2 : num;
ShowSlider(num, 100f);
yield return new WaitForEndOfFrame();
}
async.allowSceneActivation = true; //跳转场景
}
}

posted @ 2017-09-29 17:07  无止境!  阅读(360)  评论(0编辑  收藏  举报