The Assetbundle of the Unity resource solution

Source: Internet
Author: User
Tags custom name

1. What is Assetbundle

Assetbundle is a file format used by Unity Pro to store resources that can store any kind of resources that the unity engine can recognize, such as scene, Mesh, Material, Texture, Audio, NOXSS, and so on, while Assetbundle can also contain developer-defined binaries, just to change the customization file's extension to. bytes,unity it can be identified as Textasset, which can then be packaged into Assetbundle. The resources identified by the Unity engine we call asset,assetbundle a collection of asset.

Features of Assetbundle:

Compress (default), dynamic load, local cache;

2, Assetbundle VS Resource

Assetbundle as Unity's official resource renewal program, differs from the traditional resource as follows:

A, resource placed in the resources directory, resources.assets file, a single file has a 2GB limit, the first must be all downloaded;

B, Assetbundle creation needs to be created through editor script, support dynamic download, is the only content that Unity Web Caching license can cache;

3. 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 compatibility relationship as shown in the table


4. Assetbundle workflow (similar to flash loading SWF)

A, create assetbundle;

b, upload to the server;

C, the game runtime to download (or load from the local cache) Assetbundle files as needed;

D, analytic loading assets;

E, after the use is complete release;

5. Create Assetbundle

5.1. How to create Assetbundle

The Unity engine provides an API to create Assetbundle, and a total of three methods are created by compiling the pipeline Buildpipeline to create assetbundle files:

A, Buildpipeline.buildassetbundle (Mainasset:object, assets:object[], pathname:string, Options:buildassetbundleopti ONS = buildassetbundleoptions.collectdependencies | Buildassetbundleoptions.completeassets, Targetplatform:buildtarget = buildtarget.webplayer): bool

The API packages any type of assets in the editor into a assetbundle, which is suitable for the subdivision of a single large-scale scene;

B, Buildpipeline.buildstreamedsceneassetbundle (level:string[], locationpath:string, target:buildtarget): string

The API packages the resources in one or more scenarios and all of their dependencies in a stream-loaded manner into assetbundle, which is generally suitable for multi-single or multiple scenarios for centralized packaging;

C, Buildpipeline.buildassetbundleexplicitassetnames (assets:object[], assetnames:string[],pathname:string, options : buildassetbundleoptions = buildassetbundleoptions.collectdependencies | Buildassetbundleoptions.completeassets, Targetplatform:buildtarget = buildtarget.webplayer): bool

The API functionality is the same as a, but you can specify a custom name for each object when you create it. (generally less commonly used)

5.2, about Buildassetbundleoptions

A, completeassets

Make each asset itself complete, containing all the components;

B, Collectdependencies

Contains all other asset that each asset relies on;

C, Disablewritetypetree

The type information is not included in the Assetbundle. It is important to note that this option is not available if you publish Assetbundle to the Web platform;

D, Deterministricassetbundle

Each object has a unique, unchanging Hashid, so that subsequent lookups can be used to publish assetbundle incrementally;

E, Uncompressedassetbundle

Data compression is not performed. If this option is used, the Assetbundle release and load will be faster because there is no compression/decompression process, but the assetbundle will be larger, causing the download to become slower.

5.3, the dependence between assetbundle

If a resource in the game is referenced by more than one resource (for example, in-game material), creating assetbundle alone causes multiple assetbundle to contain the referenced resource (which is somewhat like the link option in the Flash compilation option), causing the resource to become larger, You can reduce the size of the final Assetbundle file by specifying a dependency between Assetbundle (decoupling the Assetbundle).

The way to do this is to call Buildpipeline.pushassetdependencies and buildpipeline.popassetdependencies to create a dependency between the assetbundle before creating Assetbundle, and it uses A stack that is then pressed into the stack depends on the elements within the stack. (Remember to pop! )

As an example:

Now there are MAT1 and mat2 two material in the game, they use the same texture Zhuanqiang

Do not use dependencies

Use dependent

6, the remote server assetbundle download

The Unity engine provides two ways to download Assetbundle files from the server, namely the caching mechanism and the non-caching mechanism.

6.1. Caching mechanism

Download the Assetbundle via the WWW.LoadFromCacheOrDownload (url:string, Version:int) interface, and the downloaded Assetbundle is automatically saved in the Unity engine's cache. This method is recommended by Unity for assetbundle download mode. When downloading Assetbundle, the interface will first look up the file in the local cache, see if it has been downloaded before, if it is downloaded, load it directly from the cache, and if not, enjoy the download from the server. The advantage of this is that you can save download time for assetbundle files, which increases the load speed of your game resources (you can also save download traffic). At the same time open more than coroutine for WWW loadfromcacheordownload operation (cache), the test opened the WWW out of the more, the faster the speed, but need to consider the timing of the machine fire platform load capacity. If you must download resources from the Internet, the number of threads is best set to 5 (other people's experience), many platforms also have their own limitations, for example, some browsers can only load 6 of colleagues and so on.

It is important to note that unity provides a default cache size that differs depending on the publishing platform (you can purchase caching license support from Unity). Currently, for Web Player, the default cache size is 50M, and the default cache size is 4GB for mobile games on the PC or on ios¥android.

Code:

www www = WWW.LoadFromCacheOrDownload (Url, 1);

yield return www;

Assetbundle ab = Www.assetBundle;

6.2. Non-caching mechanism

By creating a WWW instance to download the Assetbundle file, the downloaded Assetbundle file will not enter the unity cache. Using this method is downloaded from the remote server every time.

Code:

www www = new www (URL);

yield return www;

Assetbundle ab = Www.assetBundle;

7. Loading Assetbundle objects

7.1, through the WWW class methods and properties

Create Assetbundle directly from the WWW.assetBundle property, note: Assetbundle loaded by www must first call WWW.assetBundle before parsing asset;

7.2. Dynamic creation via API

The Assetbundle.createfromfile interface creates a memory object for a Assetbundle file from disk that only supports Assetbundle in a non-compressed format.

7.3 Dynamic creation via API

The Assetbundle.createfrommemory interface can create a Assetbundle memory object from the in-memory data stream. It is mainly used for the encryption and decryption of data.

For example:

www www = new www (URL);

yield return www;

byte[] Encrypeddata = www.bytes;

byte[] Decrypteddata = Yourdecryptionmethod (encrypeddata);//decryption function

Assetbundle ab = Assetbundle.createfrommemory (decrypeddata);

8. Load assets from Assetbundle

8.1. Loading of assets

Assetbundle.load (name:string): Object loaded from the bundle named name;

Assetbundle.load (name:string, Type:type): Object loads the named name of the specified type from the bundle;

Assetbundle.loadasync (name:string, Type:type): Assetbundlerequest asynchronously loads an object named name of the specified type from the bundle (asynchronous loading requires Unity Pro) ;

Assetbundle.loadall (Type:type): object[] Loads all objects that are contained in the asset bundle and inherit from type;

Assetbundle.loadall (): object[] Loads all objects contained in the asset bundle;

The Assetbundle.mainasset Master resource is specified (read-only) when building the resource Boundle, which makes it easy to find the main resource within the bundle. For example, you might want to have a character's prefab and include all textures, materials, meshes, and animation files. But the presets for full manipulation of characters should be your mainasset and easy to access;

For example:

Start download
www www = new www (URL);
Wait for the download to complete
yield return www;
Gets the specified master resource and instantiates
Instantiate (Www.assetBundle.mainAsset);

8.2. Load level in Assetbundle

Application.loadlevel the interface can be loaded into the corresponding scene contained in the Assetbundle file by name or index, and all previously loaded gameobject will be destroyed when the new scene is clipped;

Application.loadlevelasync the function of this interface is the same as Application.loadlevel, but the interface is asynchronous loading, that is, the main thread can continue to execute when loading;

Application.loadleveladditive the interface differs from the application.loadlevel that is not destroyed before the loaded gameobject;

Application.loadleveladditiveasync the function of this interface is the same as application.loadleveladditive, but the interface is asynchronous loading, that is, the main thread can continue to execute when loading;

For example:

www www = new www (URL);

yield return www;

Assetbundle ab = Www.assetBunlde;

Application.loadlevel ("Level1");

9, Assetbundle and memory

Memory has always been a focus for developers, if you want to understand how memory is used.

9.1. The effect of loading assetbundle on memory

When using the WWW method, the Unity engine allocates a series of memory spaces to hold WWW instance objects and Webstream data. The data includes the original Assetbundle data, the extracted assetbundle data, and a decompression Buffer for decompression. In general, decompression buffer is automatically destroyed when the original Assetbundle decompression is complete, but it is important to note that unity automatically retains a decompression buffer, which is not recycled by the system. The advantage of this is that it does not have to be too frequent to open up and destroy the decompression buffer, thereby reducing the CPU consumption to some extent.

After extracting the assetbundle into memory, developers can use the WWW.assetBundle property to get Assetbundle objects, so that various assets can be obtained to load or instantiate the assets. During loading, unity transforms the flow of data in Assetbundle into the type of information (textures, materials, objects, etc.) that the engine can recognize. Once loaded, developers can further manipulate them, such as instantiation of objects, copying and replacing textures and materials, and so on.

9.2, the Assetbundle Uninstall

1) Assetbundle.unload (TRUE) This interface forces the unload of all asset loaded in the Assetbundle, including the assetbundle mapping structure, itself to the Web A reference to stream and all resources created from Assetbundle, which is not recommended for use by the interface.

2) Assetbundle.unload (FALSE) the interface releases the serialized data within the Assetbundle, but any object instantiated from this assetbundle will be intact. Of course, you can't load more objects from this assetbundle.

Resources.unloadunusedassets the interface unloads unused assets, and the scope is the entire system.

3) for the instantiated Gameobject, the gameobject.destory () interface can be called to unload. The interface is deferred to a reasonable time for processing.

Note: This is a link that u3d has not handled well. After the completion of the WWW load resource, after the resources are instantiate, the unload of its resources, then the problem occurs, instantiate processing rendering takes a certain amount of time, although very short, but also need 1, 2 frames of time. At this point, the unload will have an impact on resource rendering, so that no stickers or other problems occur. Workaround: Write your own time to wait for the code, wait a 0.5 seconds to 1 seconds before the unload. This will not be the case of running unload in instantiate rendering.

10. About other

10.1. Embed the script in Assetbundle

Assetbundle resources on the attach if the script, packaging, the script will not be hit assetbundle, in fact, this is just a pointer-like association, if you need to move the script to Assetbundle, but also need to do some work.

First, the script is pre-compiled into assembly, Save the Assembly as a. bytes file so that unity will recognize it as textasset, you can package the Textasset into Assetbundle, which can be loaded with a reflection mechanism using the following code:

Assetbundle bundle = Wwww.assetbundle;

Textasset txt = bundle.load ("Mybinaryastext", typeof (Textasset)) as Textasset;

byte[] bytes = txt.bytes;

var assembly = System.Reflection.Assembly.Load (bytes);

It is important to note that the iOS platform does not support dynamic load scripts.

10.2, Assetbundle version control

Assetbundle is loaded using WWW.LoadFromCacheOrDownload (string url, int version, UINT CRC), where the second parameter-version can be used for versioning, This parameter forces the user to download a later version of Assetbundle from the server. We can use the third parameter CRC to achieve Assetbundle content verification, when the CRC is not 0, unity will check the Assetbundle CRC code, if not equal, the file corruption, unity will re-download the file. For CRC acquisition, (the old version does not provide a method, can only pass a wrong CRC via Loadfromcacheordownload, obtained from the log), the new version in the Buildassetbundle when the addition of an out-type parameter, This parameter returns the correct CRC code, which can be recorded for later use when it is packaged.

10.3. About sharing resources between editor and runtime

1) Unity provides a common class--noxssableobject for describing dynamic partitioning scenarios, dividing the scene by code, and packaging multiple assetbundle--> to record the partitioning information in Scriptableobject. and save to asset--> load the partition information, and then load into the assetbundle according to this partition information.

2) Use an XML file.

10.4. About Editor Extensions

Unity3d can execute your editor code through event triggering, but we need some compiler parameters to tell the compiler when it needs to trigger the code. [MenuItem (XXX)] declares above a function, tells the compiler to add a menu item to the Unity3d editor, and calls the function when it clicks the menu item. Trigger function can write any legitimate code, can be a resource batch program, you can also pop up an editor window. The code can access the currently selected content (through the selection Class) and determine the display view accordingly. Similarly, [ContextMenu ("XXX")] can add a menu item to your context menu. When you write some component script, when it is attached to a gameobject and you want to see the effect in scene view in Edit view, you can write [Executeineditmode] above the class to inform the compiler. Functions such as Ongui and update of this class are also called in edit mode. We can also use [Addcomponentmenu ("xxx/xxx")] to associate the script with the Component menu and click on the menu item to add the component script for Gameobject.

To avoid unnecessary inclusions, the Unity3d Runtime and editor classes are stored in different assemblies (Unityengine and Unityeditor). Scripts in the editor directory are compiled after other scripts, which makes it easier for you to use those runtime content. The scripts in those directories are not accessible to the contents of the editor directory. So, you'd better write your editor script in the editor directory.

10.5, about the difference release

The parameters for creating Assetbundle are described in 5.2, where the D option allows the same content to be published two times at the same time, and we choose this parameter when creating Assetbundle, so we can do the difference. The test data is as follows:

The parameter is not selected:

After you select this parameter:

10.6, about the application of the project

The project uses Assetbundle to do the development can use the macro to isolate, the interface encapsulation uses the asynchronous interface as far as possible, through the reference counting cache mechanism, determines AB's release time. The general flow is as follows:

A, determine the number of times to load AB (resources)

b, Load AB

C, after successful, based on the resource URL reference count minus the corresponding number of resources

D, when the reference count is 0, call Assetbundle's unload (false)

Where the code is used, the loaded objects can be obtained through the encapsulated GetObject, and the resources can be freed by invoking the unloadunusedassets after the use is complete.

10.7. Particle size Control of assetbundle

The smaller the granularity of AB, the smaller the redundancy of the differential update, and the greater the granularity, the greater the redundancy of the differential update. However, it is not said that the smaller the granularity of the better, the granularity is small, (runtime) loading will increase the number of Io, the number of decompression (AB generally choose the compression format) and the number of memory applications, resulting in a longer load time. So granularity control is a process of choosing time and space balance. After experiments, there is a general data can be used for reference, 1M or so Assetbundle package loading performance best, redundancy is acceptable.

10.8, about the compression selection of Assetbundle

There are two main differences between assetbundle compression and non-compression:

A, external memory (the size of the installation package or the size of disk space after installation)

B, the choice of loading mode (can use synchronous method)

If some of the performance requirements are particularly high, the resources of a small AB can be non-compressed, through the CreateFromFile load AB package, the highest performance without generating a lot of memory. For other resource files, compression processing is recommended, compression and non-compression on disk occupancy will be about 4 times times the size difference, if all in a non-compressed format, it may cause your disk occupation to a very scary magnitude.

10.9. Application of Assetbundle in external memory optimization

After the installation of the disk composition is basically the memory value of the resources (Resources directory Resource), a particle, a true color of the 1024*1024 image placed in the resources directory installed after the memory used to occupy 4M (4*1024*1024). If your game is a 2D, and contains a lot of picture resources, this will make your installation package on the user's machine requires a lot of disk space, here you can put them into the ab bag to put on the user's phone, so the disk occupies a lot smaller.

The Assetbundle of the Unity resource solution

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.