一共有兩種方法下載下傳AssetBundles資料資源:
無緩存:這種方法使用将建立一個WWW類,下載下傳完的資料無法在本地unity3d的緩存目錄中進行儲存。
有緩存:使用WWW.LoadFromCacheOrDownload的方法,下載下傳完的資料将在unity3d的本地緩存目錄中進行儲存。Web浏覽器通常允許緩存大小達到50MB,PC和MAC的本地應用,IOS和Android應用都允許緩存達到4GB大小。
下面是不含緩存的代碼:
using System;
using UnityEngine;
using System.Collections; class NonCachingLoadExample : MonoBehaviour {
public string BundleURL;
public string AssetName;
IEnumerator Start() {
// Download the file from the URL. It will not be saved in the Cache
using (WWW www = new WWW(BundleURL)) {
yield return www;
if (www.error != null)
throw new Exception("WWW download had an error:" + www.error);
AssetBundle bundle = www.assetBundle;
if (AssetName == "")
Instantiate(bundle.mainAsset);
else
Instantiate(bundle.Load(AssetName));
// Unload the AssetBundles compressed contents to conserve memory
bundle.Unload(false);
}
}
下面是含緩存的代碼,系統建議利用WWW.LoadFromCacheOrDownload類進行下載下傳:
using System.Collections;
public class CachingLoadExample : MonoBehaviour {
public string BundleURL;
public string AssetName;
public int version;
void Start() {
StartCoroutine (DownloadAndCache());
IEnumerator DownloadAndCache (){
// Wait for the Caching system to be ready
while (!Caching.ready)
yield return null;
// Load the AssetBundle file from Cache if it exists with the same version or download and store it in the cache
using(WWW www = WWW.LoadFromCacheOrDownload (BundleURL, version)){
yield return www;
if (www.error != null)
throw new Exception("WWW download had an error:" + www.error);
AssetBundle bundle = www.assetBundle;
if (AssetName == "")
Instantiate(bundle.mainAsset);
else
Instantiate(bundle.Load(AssetName));
// Unload the AssetBundles compressed contents to conserve memory
bundle.Unload(false);
這樣,下載下傳之前系統會現在緩存目錄中查找, WWW.LoadFromCacheOrDownload函數的第二個參數表示版本号,當要下載下傳的資料在緩存目錄中不存在,或者存在,但版本号比較低時,系統才會下載下傳新的資料資源,并替換到緩存中的原資料資源。
現在來完成上一篇中的執行個體,在項目視圖(Projection View)中,建立Script目錄,利用上面的兩段源代碼,分别建立名為CachingLoadExample和NonCachingLoadExample的C#腳本。
在unity3d編輯器中建立空物體,菜單GameObject - CreateEmpty,把CachingLoadExample腳本拖動到GameObject上。在層級視圖中(Hierarchy View)選中GameObject,在右邊的監視視圖(Inspector View)中,把CachingLoadExample腳本的BundleURL變量值指定到Cube.unity3d檔案所在位置(輸入絕對路徑,需根據自己存放的目錄手動修改),例如:file://C:/UnityProjects/AssetBundlesGuide/Assets/AssetBundles/Cube.unity3d,現在運作unity3d,就能夠實作動态加載Cube物體了。