缓存方式
使用WWW.LoadFromCacheOrDownload接口。AssetBundles将保存在本地设备的Unity的缓存文件夹中。WebPlayer 有50MB的缓存上限,PC/Mac/Android/IOS应有有4 GB的缓存上限。这种方式也是加载AssetBundle推荐的方式。我们使用这种方式来实践一下。在Scripts文件夹中新建脚本:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
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/
本文转自jiahuafu博客园博客,原文链接http://www.cnblogs.com/jiahuafu/p/6594404.html如需转载请自行联系原作者
jiahuafu