Unity 進度條
協程異步加載場景
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
using System;
using UnityEngine.UI;
public class LoadScence : MonoBehaviour
{
Slider slider;
Text text;
private void Awake()
{
slider = transform.Find("Slider").GetComponent<Slider>();
text= transform.Find("Text").GetComponent<Text>();
}
private void Start()
{
StartCoroutine(StartLoading());//開啟協程
}
private IEnumerator StartLoading()//協程
{
int displayProgress = ;
int toProgress = ;
AsyncOperation scene = SceneManager.LoadSceneAsync();//異步加載場景
scene.allowSceneActivation = false; //不允許場景在準備就緒後立即被激活
while (scene.progress < f)
{
toProgress = (int)scene.progress * ;//progress 0-1
while (displayProgress < toProgress)
{
++displayProgress;
slider.value = displayProgress *f;
this.text.text = "Loading..." + displayProgress.ToString()+"%";
yield return new WaitForEndOfFrame();//等待直到所有的錄影機和GUI被渲染完成
}
}
toProgress = ;
while (displayProgress <= toProgress)
{
yield return new WaitForEndOfFrame();//等待直到所有的錄影機和GUI被渲染完成
++displayProgress;
slider.value = displayProgress*f;
this.text.text = "Loading..." + displayProgress.ToString() + "%";
}
scene.allowSceneActivation = true;//允許場景在準備就緒後立即被激活
}
}
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiQ3chVEa0V3bT9CX5RXa2Fmcn9CXwczLcVmds92czlGZvwVP9EUTDZ0aRJkSwk0LcxGbpZ2LcBDM08CXlpXazRnbvZ2LcRlMMVDT2EWNvwFdu9mZvwFeONzY2p0MZZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39zM5cTOyMzMyETNwATM3EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)