Unity Assetbundle Notes

Source: Internet
Author: User

1. Getting Started:

Resources: Indicates that u3d automatically to the resources into a assetbundle package, all the folders placed under resources will be played into a assetbundle package, the resource is very large, The Resources folder has a maximum of 2G of memory on the real Machine (Professional Edition will increase memory)

Assetbundle Package: Actually can be regarded as a compressed package (there is a fixed format), by default, using LZMA compression compression of the resource files, and compressed zip, but the format is changed

The Unity3d engine provides us with three compression strategies to handle assetbundle compression, namely:

1. Lzma Format:

By default, the Assetbundle generated by the package will be compressed. In u3d, the standard compression format for Assetbundle is Lzma (Lzma is a serialized stream file), so by default the outgoing Assetbundle package is in the compressed state in LZMA format, which needs to be uncompressed before using Assetbundle. Assetbundle with LZMA format has the smallest package volume (high compression ratio), but increases the decompression time accordingly.

2. LZ4 Format:

The version after Unity5.3 increases the LZ4 format compression, because the compression ratio of LZ4 is general, so the volume of the Assetbundle package after compression is larger (the algorithm is based on chunk).

3, do not compress

The difference between resources and Assetbundle:

1, Resources: There is a 2G limit, does not support dynamic update (take Android as an example)

A, on-line, resources inside the resource are inside the APK, can only read can not write

B, Streamingassets and DataPath are all in the APK, the APK is a compressed package, the contents of which can only be read and not written, so this restriction determines that the resources can not support hot update

2, Persistpath (Support heat more):

A, manual packaging only

B, Packaging method:

Before 1, 4.0, a packaged dependency must be manually

After 2 or 5.0, this dependency is automatically

Create Assetbundle:assetbundle to package any resource into assetbundle (if it is a file that unity does not recognize, it can be packaged by changing the suffix)

1, in the lower right corner of any game object has Assetbundle, the first is the package name, the second suffix (unrecognized object can not be modified, modify the suffix to become recognizable objects)

Update process:

1, the Code update: Hot update

2. Update of resources: Assetbundle update

A, create Assetbundle

b, the assetbundle into a zip file, put into the streamingassetpath inside

C, the need to update the Assetbundle first upload to the server, if the server has an update (compared with the server version), the server Assetbundle package download (zip file), and then extracted into the Persistentpath

D: Load: Determine whether there is this resource in the Persistentpath, if not read streamingassetpath inside, if there is, directly read Persistentpath in the

1. Loadasset: Load the specified resource from the resource bundle

2. Loadallasset: Load resources in the current resource bundle

3. Loadassetasync: Load resources asynchronously from the resource bundle

3. Resource unload: The Unload method is used in the Resource Unload section

Unload:

A, this method unloads all the resources contained in the bundle in memory when the payload is loaded.

b, when the passed-in argument is true, not only the resources contained in the in-memory Assetbundle object are destroyed; The objects in the game are also destroyed based on the resource instantiation

C, when the passed-in parameter is false, only the resources contained in the Assetbundle object in memory are destroyed

    

Buildpipeline.buildassetbundles (OutputPath, buildassetbundleoptions.appendhashtoassetbundlename| Buildassetbundleoptions.chunkbasedcompression, Editoruserbuildsettings.activebuildtarget);

  

Assetbundle platform and cross-platform

Assetbundle is suitable for a variety of platforms, including Web applications, mobile applications, desktop applications, etc., can be dynamically updated, but different platforms use Assetbundle is not the same, when creating an offline Assetbundle need to specify the target platform by parameters, The related relationships are shown in the table:

    

IOS: Packaging on Mac version of Standlone

Windows: Playing Android, PC, Webplayer

BuildPipeline.BuildAssetBundles():   1、第一个参数:AssetBundle输出到哪一个文件夹   2、第二个参数:枚举类型,可以选择多个参数,多个参数之间可以用“|“隔开     a、CompleteAssets:保证资源的完备性,默认开启     b、CollectDependencies:用于搜集资源的依赖项,默认开启       和完整性有点相像,会把游戏物体所依赖的资源一起进行打包,防止有些被依赖的资源没有被打进去     c、DeterministicAssetBundle:用于为资源维护固定ID,默认开启       所以的资源都有固定的标记的,在资源的mate文件中的guid:64位组成的字符串,电脑里是随机生成并且唯一,每一个文件的唯一标识     d、ForceRebuildAssetBundle:用于强制重打所有AssetBundle文件,5.3以后新增       资源更新了,重新打包,将以前的资源包丢弃     e、IgnoreTypeTreeChanges:用于判断AssetBundle更新时,是否忽略TypeTree的变化,新增       打包时是否忽略父子关系     f、AppendHashToAssetBundleName:用于将Hash值添加在AssetBundle文件名之后,开启这个选项可以直接通过文件名来判断哪些Bundle的内容进行了更新       (4.X下普遍需要通过比较二进制等方法来判断,但在某些情况下即使内容不变重新打包,Bundle的二进制也会变化),新增       在包名后缀名后面添加一个Hash表     g:ChunkBasedCompression:用于使用LZ4格式进行压缩,5.3新增

First, how to organize Assetbundle:

Before unity5, packaging needed to find its own dependencies, and then it needed to press the AB stack in the order of the topology diagram, so that the dependence (the existing AB ability in the stack) could be used in the final hit of AB.

After unity5.x, packaging becomes simple, but how to organize assetbundle still needs pondering and planning.
First we need to know: AB, asset and resource relationships: An AB consists of 1 or more asset, and one asset may not rely on other asset (that is, all the resources it needs), It is also possible to rely on other asset (including some resources and references to other asset where AB).
Second, using asset and AB: To use a asset, you need to load all the dependent asset of the asset (iteration down, load all relevant AB), then load your own AB and finally take out the asset to use.
So, to use a asset, all the associated assetbundle mirrors need to be loaded into memory. This will require us to study AB's plan. And the way to play AB also affects the total size of AB, even under Unity5.
The documentation provides 3 dozen AB solutions:
1. Logical entity classification, that is, according to the functional module classification, (generally speaking, different functions of different AB, so you can open a function to download an AB) such as the first large-scale: UI module, role module, Scene module, etc.,
The UI module is also based on the specific function modules: for example, each copy of the UI is different, then each copy of the UI can be played as a separate AB;
The role module is each role including its dependencies, such as mesh,model,animation,texture and so on into an ab;
The scene module can be divided into multiple slices of a scene, each of which is equivalent to a "submodule", separate into AB, multiple scenes shared slices.
2. According to the type of resources to fight AB: such as sound effects into an AB, internationalized text into 1 AB, etc., the document says this method is a good way to play multi-platform AB, such as sound effects AB in all platforms are the same can be reused, and shader platform is not reusable
And in this method, because the original resources (such as texture) are rarely changed, it is advantageous for the version update (less increment). This method I do not understand, the feeling is to refine the AB granularity to the original resource level (textures, sound effects, grids, etc.), they have on different platforms to maintain the same, some platform differentiated, but the basic will not change.
3. According to "simultaneous loading" to hit AB, that need to load the same resources into the same AB. For example, each scene includes everything it relies on to make an AB.
No matter what scheme you use (generally use a little bit, such as the 3rd to play the scene, the 1th to hit the various systems (i.e. functions) of resources, etc.), in order to reduce the size of AB, delta AB size, load time and run-time memory consumption, you need to pay attention to the following details:
1. Frequently changing asset should not enter a assetbundle with stable asset; small increments AB
2. If a stable large/multi-asset contains frequently changing resources, the resources should be individually hit AB; small increments AB
3. When using the common load of things such as model and its texture,material,animation should be scored in a assetbundle, so the role of each AB; Reduce load time
4. If multiple AB relies on a asset or resource, the asset or resource should be individually hit AB; small AB, save memory
5. If 2 asset are loaded at the same time, you should play AB separately; Save the memory
6. Combine the AB of small asset that are often loaded at the same time into large ab; reduce load time

Second, play AB's parameter selection and loading AB scheme:

1. Checklist:

1) When you hit AB, each AB will have an additional. manifest file that describes the information about the AB, including
CRC code, (file hash) a single hash for all assets in AB, (type tree hash) a single hash for all types in AB, (class types) all Clas s types in AB, (asset names) all asset paths in AB.
This file is only used to generate Delta AB, not necessary for runtime, so there is no need to break into the installation package, the dependency can be found in 2.
2) and generate a. manifest file in the output folder in the input parameters of the AB, which includes all the AB paths and their dependencies, which is used when loading resources at run time, because loading resources requires loading dependencies first.

Compression mode of 2.AB

AB has 3 compression methods (of course you can also customize the compression algorithm, but not necessary), one is uncompressed uncompressedassetbundle, one is the block compression LZ4 (chunkbasedcompression), one is the maximum compression Lzma (None )
Load without compression the fastest, followed by block compression (only need to decompress the part of AB can be loaded, and no compression is comparable), and finally LZMA (need to fully decompress AB), of course, the size of the AB is reversed (lzma:50-60%,lz4:70%).
General Local AB recommended to store in LZ4 format, small and fast, need to download the network with LZMA and use loadfromcacheordownload to load it, In this way the local becomes LZ4 (Loadfromcacheordownload is extracted directly when the data stream is accepted, without additional time).

Several interfaces for 3.AB loading

1) Load AB file (here is the ab file after build, if the build is also encrypted and so on can not be directly loaded) there are several ways:
WWW: Input url,ab in www.assetBundle; PS: If AB is local, the URL is prefixed with file:///
WWW.LoadFromCacheOrDownload: Input url,ab in www.assetBundle; PS: If AB is local, the URL is prefixed with file:///
Loadfrommemory (Async): input is bytes[], return is ab;ps:bytes get general use WWW, also can direct file.readallbytes, anyway get the file of the byte stream.
LoadFromFile (Async): input is path,ab in Assetbundlecreaterequest.assetbundle;

Unitywebrequest: The document says this method is better than WWW, usage is similar, but because www is more mature, and www we basically just used to load local bytes resources, and this method after 5.4 version, we do not use.
In the network resources download aspect our project uses the HttpWebRequest which the C # provides
2) Loading non-. assetbundle files such as. bytes,.jpg,.png,.txt,.ogg,.mp3 files are generally loaded using www:
The WWW.bytes,WWW.texture,WWW.text,WWW.audioClip data is stored separately in the load.

If the original is. Assetbundle, encrypt into. Bytes, first www add bytes, then loadfrommemory;

If the original is. bytes or other custom data type, such as Xml,json, etc., Play AB into. Assetbundle, then add the Assetbundle, then load the asset, and finally strong into the Textasset type, then your data can be removed from it, unity often regard these data as Textasset type;

In short, for the special file format, we used to test its loading method before, basically in the WWW and textasset this piece of consideration, look at the data in which variables, a test will know.

4. Select the compression mode + load interface for the various ways described in 2 and 3

The document makes the following recommendations based on the characteristics of each function for memory and CPU consumption:
1. For the AB in the installation package, use LoadFromFile (Async) +chunkbasedcompression as much as possible, as it fits quickly with the chunkbasedcompression (can compress 30%+ and does not require additional decompression when loading) , if the compression format of AB is Lzma (i.e. option=none), LoadFromFile (Async) requires additional decompression and re-compression (pressure is LZ4);
2. For network resources, Try to use WWW.LoadFromCacheOrDownload, and resources as far as possible with the default Lzma compression method, because this can save traffic, and this function in the receiving network stream when the convection decompression, for the LZ4 (that is, AB pressure is not different), and loading LZ4 do not need additional decompression.
3. For the encrypted AB, you need to use WWW to load the file into bytes, then decrypt and then use Loadfrommemory[async] to load the AB (this is probably the only scene of Loadfrommemory[async])
4. If a custom compression algorithm is used, select Uncompressedassetbundle not compress to build AB, then unzip the data before loading, then LoadFromFile (Async)
Summary: My current project is using LZMA build AB (do not use LZ4 reason may be not in-depth understanding, may also be covet Lzma small package body, also may be the load is mostly small Ab,lzma decompression and pressure LZ4 consumption can endure), with LoadFromFile (Async) Load. Assetbundle,www+loadfrommemory (Async) loads the encrypted ab.bytes, loading the original image with WWW.

Third, if the management Assetbundle

Usage of 1.assetbundle.unload (true/false):
True will destroy the AB, the asset, which is added by AB, and the gameobj (which may be referred to asset only), which is instantiated by asset;
False just unload the AB, the official document described as the AB and asset,gobj link disconnect, that the latter themselves delete themselves, if the load asset is the new asset, and the original asset independently coexist in memory;
Here are two points to be clear:
1.AssetBundle loaded out without unload then its image has been in memory, again loading will error, can unload off reload or hold it, do not reload;
2.false to unload asset need to be instantiated by the Gobj are destroyed (the reference is empty), and then Resource.unloadunusedassets unloading, gobj destroy can;
Official documentation It is suggested that the time to select the True,true call may be to cut the map or the asset reference to 0 o'clock, and if False is selected, the asset can only be unloaded if it is 2.
But the official document didn't see? one point is what to do if the reload should be done before calling unload (true).
1. In fact, only need to save a pool on the top, the pool of elements corresponding to a assetbundle, loading AB First look at the pool is not, there is the direct use of it to getasset and instantiation, and reference +1, when the instantiation of something destroy the AB reference minus one When the reference becomes 0 o'clock unload (true).
2. But this approach is mainly used to deal with instantiated Gameobject resources, for some resources such as audioclip,text, scenes, custom data, etc. generally rarely loaded frequently, so that we load ab out directly unload (false), and then when it is not used, The corresponding asset reference is empty, it can be unloaded at Unloadunusedasset (when the scene is cut by default, it is usually called once in the program)
3. Official documentation is recommended to use unload (true), is to avoid multiple copies of memory asset and asset can not be unloaded in a timely manner, if the resources are rarely loaded such as those in 2, with unload (false) better, As for the Unloadunsedasset call can be called manually after the resource is used (when the resource consumption is clear), you can also hand over to the game unloading system (timed call Unloadunusedasset) or cut the scene.

One of my options:

A. For resources that are not frequently loaded (mostly), we unload (false) after loading, so that the memory image can be released quickly, and when the loaded resource is no longer used (the reference is empty), the asset can be identified as unsedassets and unloaded;

B. For frequently loaded resources (small portions), we have a pool in the upper layer, there is a stringtoasset dictionary, the dictionary is only asset, that is, even the frequently loaded resources we have to load the asset with unload (false) to unload the memory image, Just keep the loaded resources for instantiation/referencing, here we need to make a reference count, because the dictionary always references the resource, and when the reference count is 0 o'clock we need to remove it from the dictionary.

Under the guidance of a-B + timed call RESOURCES.UNLOADUNUSEDASSETS,GC. Collect should be able to keep the memory as clean as possible. Which resources are frequently loaded which are not frequently loaded, what is the standard? This requires a specific test to get the relevant standards and performance of the relationship to make decisions, and game logic, and resources related, and experience related, need to write tools to determine.
Summary: Assetbundle management mainly grab a few interfaces can Assetbundle.unload (true/false), RESOURCES.UNLOADUNUSEDASSETS,GC. Collect,destroy, but to really understand them requires a deep understanding of unity's memory management mechanisms for assetbundle,asset, resources, and so on, which can be referenced in this article:

Http://www.cnblogs.com/88999660/archive/2013/03/15/2961663.html

Ps (doubts and additions)

Assetbundle Variant:ab variant, generally used to solve the "polymorphism" problem, such as resources have hd,ld, picture to adapt to a variety of devices need different compression format, can be studied.

Unity Assetbundle Notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.