那么下面就举一个AssetBundle的例子:
Assetbundle的内存处理
以下载Assetbundle为例子,聊一下内存的分配。匹夫从官网的手册上找到了一个使用Assetbundle的情景如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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;
//WWW是第1部分
if
(www.error !=
null
)
throw
new
Exception(
"WWW download had an error:"
+ www.error);
AssetBundle bundle = www.assetBundle;
//AssetBundle是第2部分
if
(AssetName ==
""
)
Instantiate(bundle.mainAsset);
//实例化是第3部分
else
Instantiate(bundle.Load(AssetName));
// Unload the AssetBundles compressed contents to conserve memory
bundle.Unload(
false
);
}
// memory is freed from the web stream (www.Dispose() gets called implicitly)
}
}
|
内存分配的三个部分匹夫已经在代码中标识了出来:
- Web Stream:包括了压缩的文件,解压所需的缓存,以及解压后的文件。
- AssetBundle:Web Stream中的文件的映射,或者说引用。
- 实例化之后的对象:就是引擎的各种资源文件了,会在内存中创建出来。
那就分别解析一下:
1
|
WWW www = WWW.LoadFromCacheOrDownload (BundleURL, version)
|
- 将压缩的文件读入内存中
- 创建解压所需的缓存
- 将文件解压,解压后的文件进入内存
- 关闭掉为解压创建的缓存
1
|
AssetBundle bundle = www.assetBundle;
|
- AssetBundle此时相当于一个桥梁,从Web Stream解压后的文件到最后实例化创建的对象之间的桥梁。
- 所以AssetBundle实质上是Web Stream解压后的文件中各个对象的映射。而非真实的对象。
- 实际的资源还存在Web Stream中,所以此时要保留Web Stream。
1
|
Instantiate(bundle.mainAsset);
|
通过AssetBundle获取资源,实例化对象
最后各位可能看到了官网中的这个例子使用了:
1
2
|
using(WWW www = WWW.LoadFromCacheOrDownload (BundleURL, version)){
}
|
这种using的用法。这种用法其实就是为了在使用完Web Stream之后,将内存释放掉的。因为WWW也继承了idispose的接口,所以可以使用using的这种用法。其实相当于最后执行了:
1
2
|
//删除Web Stream
www.Dispose();
|
OK,Web Stream被删除掉了。那还有谁呢?对Assetbundle。那么使用
1
2
|
//删除AssetBundle
bundle.Unload(
false
);
|
ok,写到这里就先打住啦。写的有点超了。有点赶也有点临时,日后在补充编辑。