緩存方式
使用WWW.LoadFromCacheOrDownload接口。AssetBundles將保存在本地設備的Unity的緩存文件夾中。WebPlayer 有50MB的緩存上限,PC/Mac/Android/IOS應有有4 GB的緩存上限。這種方式也是加載AssetBundle推薦的方式。我們使用這種方式來實踐一下。在Scripts文件夾中新建腳本:
using System;
using UnityEngine;
using System.Collections;
public class CacheBundle : MonoBehaviour
{
public static readonly string BundleURL =
#if UNITY_ANDROID
"jar:file://" + Application.dataPath + "!/assets/MyAssetBundles/shape/cube";
#elif UNITY_IPHONE
Application.dataPath + "/Raw/MyAssetBundles/shape/cube";
#elif UNITY_STANDALONE_WIN || UNITY_EDITOR
//我們將加載以前打包好的cube
"file://" + Application.dataPath + "/MyAssetBundles/shape/cube";//由於是編輯器下,我們使用這個路徑。
#else
string.Empty;
#endif
//還記得嗎?在cube這個AssetBundle中有兩個資源,Cube1和Cube2
private string AssetName = "Cube2";
//版本號
public int version;
void Start()
{
StartCoroutine(DownloadAndCache());
}
IEnumerator DownloadAndCache()
{
// 需要等待緩存准備好
while (!Caching.ready)
yield return null;
// 有相同版本號的AssetBundle就從緩存中獲取,否則下載進緩存。
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;
GameObject cube = Instantiate(bundle.LoadAsset(AssetName)) as GameObject;
cube.transform.position = new Vector3(1.5f, 0f, 0f);
// 卸載加載完之后的AssetBundle,節省內存。
bundle.Unload(false);
} //由於使用using語法,www.Dispose將在加載完成后調用,釋放內存
}
}
博主注:版本號可按天來,比如
int version;
version = DateTime.dayOfYears;
http://baizihan.me/2016/03/unity-assetbundle03/
