unity怎么知道一个场景是否加载完成

如题所述

第1个回答  2016-03-19
需要一个场景一个场景的加载,这时候可以使用 WWW 先通过 HTTP 加载场景到本地缓存,然后再使用 Application.LoadLevel 或者 Application.LoadLevelAsync 函数加载场景,使用这种加载方式,不仅不需要 Build Settings - Add Current 处理加载场景,进度条的显示也更加容易,但是使用这种方式,需要先把场景打包成 unity3d(查看详情) 或者 assetbundle(查看详情) 文件。

  1、先把测试场景搭建好,
  2、然后添加一个 C# 脚本,取名 Usewww.cs,全部代码如下:
  复制代码代码如下:
  using UnityEngine;
  using System.Collections;
  public class UseWww : MonoBehaviour
  {
  public UISlider progressBar;
  public UILabel lblStatus;
  private WWW www;
  private string scenePath;
  void Awake()
  {
  this.scenePath = "file:///" + Application.dataPath + "/Assets/MainScene.unity3d";
  // 开始加载场景
  this.StartCoroutine (this.BeginLoader ());
  }
  void Update()
  {
  if (this.www != null this.progressBar != null !this.www.isDone)
  {
  // 更新进度
  this.progressBar.value = this.www.progress;
  }
  }
  private IEnumerator BeginLoader()
  {
  this.lblStatus.text = "场景加载中,请稍候。。。";
  // 加载场景使用 www.LoadFromCacheOrDownload,函数,这样加载完成才能使用 Application.LoadLevel 或者 Application.LoadLevelAsync
  this.www = www.LoadFromCacheOrDownload (scenePath, Random.Range(0, 100));
  yield return this.www;
  if(!string.IsNullOrEmpty(this.www.error))
  {
  this.lblStatus.text = "场景加载出错!";
  }
  if (this.www.isDone)
  {
  this.lblStatus.text = "场景正在初始化,请等待。。。";
  Application.LoadLevelAsync("MainScene");
  }
  }
  }

  3、然后把这个脚本挂载到游戏场景的一个对象中,设置好相关属性,  
  4、运行游戏,可以查看进度条的加载情况,当加载完成,自动跳转到下一个场景中,
  5、因为前面封装了一个 WWW 加载管理器(查看详情),可以直接拿来使用,建立一个新的 C# 脚本,取名 UseWwwLoaderManager.cs,全部代码如下:

  复制代码代码如下:
  using UnityEngine;
  using System.Collections;
  public class UseWww : MonoBehaviour
  {
  public UISlider progressBar;
  public UILabel lblStatus;
  private WWW www;
  private string scenePath;
  void Awake()
  {
  this.scenePath = "file:///" + Application.dataPath + "/Assets/MainScene.unity3d";
  // 开始加载场景
  this.StartCoroutine (this.BeginLoader ());
  }
  void Update()
  {
  if (this.www != null this.progressBar != null !this.www.isDone)
  {
  // 更新进度
  this.progressBar.value = this.www.progress;
  }
  }
  private IEnumerator BeginLoader()
  {
  this.lblStatus.text = "场景加载中,请稍候。。。";
  // 加载场景使用 www.LoadFromCacheOrDownload,函数,这样加载完成才能使用 Application.LoadLevel 或者 Application.LoadLevelAsync
  this.www = www.LoadFromCacheOrDownload (scenePath, Random.Range(0, 100));
  yield return this.www;
  if(!string.IsNullOrEmpty(this.www.error))
  {
  this.lblStatus.text = "场景加载出错!";
  }
  if (this.www.isDone)
  {
  this.lblStatus.text = "场景正在初始化,请等待。。。";
  Application.LoadLevelAsync("MainScene");
  }
  }
  }
  6、然后把原先的脚本从场景移除,挂载这个新的脚本,运行游戏,可以看到与上面同样的加载效果。本回答被提问者采纳
相似回答