using UnityEngine; using System.Collections; public class ChangeScene : MonoBehaviour { // 加载场景的名称 public string levelName; // ngui滚动条 public UIScrollBar progressBar; // 异步操作 对象 private AsyncOperation async; void OnClick() { // 在这里开启一个异步任务, // 进入loadScene方法。 StartCoroutine(loadScene()); } // 返回值一定是 IEnumerator IEnumerator loadScene() { // 打开滚动条 progressBar.gameObject.SetActive(true); // 异步读取场景。 async = Application.LoadLevelAsync(levelName); // 读取完毕后返回, 系统会自动进入场景 yield return async; } // 因为在异步读取场景, // 所以这里我们可以刷新UI void OnGUI() { if (async != null) { // 在这里计算读取的进度, // progress 的取值范围在0.1 - 1之间, 但是它不会等于1 // 也就是说progress可能是0.9的时候就直接进入新场景了 // 所以在写进度条的时候需要注意一下。 // 为了计算百分比 所以直接乘以100即可 // 最后,把值赋给滚动条,就可以观察看到加载进度了 progressBar.value = async.progress; Debug.Log((int)(progressBar.value * 100)); } } }
有个问题,上面的加载总是会卡主,滚动条显示不全就加载下一个场景。
|
|
asyncOperation.allowSceneActivation = false ; |
另外,把刷新UI放在了UpDate中,竟然平滑了许多……
最后,async.progress永远在只能达到0.89,所以async.isDone()不可能为true。应该是Bug。
using UnityEngine; using System.Collections; /** * 异步加载场景 */ public class LeaveLoad : MonoBehaviour { // 需要加载的场景名称 public string leaveName; // 滚动条 public UIProgressBar progressbar; private AsyncOperation async; void OnClick() { StartCoroutine (loadScene()); } IEnumerator loadScene() { if (!string.IsNullOrEmpty (leaveName)) { progressbar.gameObject.SetActive(true); async = Application.LoadLevelAsync(leaveName); async.allowSceneActivation = false; //async = Application.LoadLevelAdditiveAsync(leaveName); yield return async; } } void OnGUI() { } IEnumerator Do(float f) { yield return new WaitForSeconds (f); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (async != null) { if (progressbar.value >= 0.89f) { progressbar.value = 1f; //Do (1); async.allowSceneActivation = true; } else { progressbar.value = async.progress; Debug.Log((int)(progressbar.value * 100)); } } } }