Assetbundle的内存处理

那么下面就举一个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)
     }
}

内存分配的三个部分匹夫已经在代码中标识了出来:

  1. Web Stream:包括了压缩的文件,解压所需的缓存,以及解压后的文件。
  2. AssetBundle:Web Stream中的文件的映射,或者说引用。
  3. 实例化之后的对象就是引擎的各种资源文件了,会在内存中创建出来。

那就分别解析一下:

1
WWW www = WWW.LoadFromCacheOrDownload (BundleURL, version)
  1. 将压缩的文件读入内存中
  2. 创建解压所需的缓存
  3. 将文件解压,解压后的文件进入内存
  4. 关闭掉为解压创建的缓存
1
AssetBundle bundle = www.assetBundle;
  1. AssetBundle此时相当于一个桥梁,从Web Stream解压后的文件到最后实例化创建的对象之间的桥梁。
  2. 所以AssetBundle实质上是Web Stream解压后的文件中各个对象的映射。而非真实的对象。
  3. 实际的资源还存在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,写到这里就先打住啦。写的有点超了。有点赶也有点临时,日后在补充编辑。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值