那麼下面就舉一個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,寫到這裏就先打住啦。寫的有點超了。有點趕也有點臨時,日後在補充編輯。