Unity3D 加載場景有很多種方式,做一些小的 DEMO 的時候往往是直接使用 Application.LoadLevel 或者 Application.LoadLevelAsync 函數加載場景,具體可查看(http://www.xuanyusong.com/archives/1427),但是這種辦法不適合在真正的 Unity3D 開發中,因為前一種需要把所有的場景都打包,這在某些情況下是不現實的,比如開發頁游,我們不可能把所有的場景都打包讓用戶下載,我們需要一個場景一個場景的加載,這時候我們可以使用 WWW 先通過 HTTP 加載場景到本地緩存,然后再使用 Application.LoadLevel 或者 Application.LoadLevelAsync 函數加載場景,使用這種加載方式,不僅不需要 Build Settings -> Add Current 處理加載場景,進度條的顯示也更加容易,但是使用這種方式,需要先把場景打包成 unity3d(查看詳情) 或者 assetbundle(查看詳情) 文件。
先把測試場景搭建好,如圖:
然后添加一個 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");
}
}
}
然后把這個腳本掛載到游戲場景的一個對象中,設置好相關屬性,如圖:
運行我們的游戲,可以查看進度條的加載情況,當加載完成,自動跳轉到下一個場景中,如圖:
因為前面我封裝了一個 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");
}
}
}
然后我們把原先的腳本從場景移除,掛載這個新的腳本,如圖:
運行游戲,可以看到與上面同樣的加載效果。
百度網盤下載地址:http://pan.baidu.com/s/1hq7pgd2 密碼: lc4y