一共有两种方法下载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;
using UnityEngine;
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物体了。