1. 程式人生 > >u3d 異步加載場景以及進度條的顯示

u3d 異步加載場景以及進度條的顯示

onclick cli star lec build transform yield ddl cnblogs

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; //跳轉場景
}
}

u3d 異步加載場景以及進度條的顯示