Assetbundle of Unity Resource Packaging

Source: Internet
Author: User

The original copyright of this article belongs to Csdn Janeky all. Reprint please specify the original author and source, to show respect.

Janeky

Original: http://blog.csdn.net/janeky/article/details/17652021

If this article is helpful to you, stay tuned for the author's "Unity Hand Tour" series of tutorials.

In the operation of the hand tour, updating resources is not the least.

Resource management The first step is resource packaging. Traditional packaging can be made into a preset prefab of all objects. Packaged into a scene. Today we come together to study the official recommended Assetbundle. It is a resource packaging strategy provided by Unity (Pro). With Assetbundle, you can package nearly all of your resources to facilitate client updates to download new resources.

(Reprint please specify original source http://blog.csdn.net/janeky/article/details/17652021)

    • Create Assetbundle
1. Create an empty prefab, name the cube, then create a cube and pull it to the newly created prefab
2. Create a new script ExportAssetBundles.cs (code from the official document), saved in the Asset/editor folder
    Adding a menu in the Unity Editor    [MenuItem ("Assets/build assetbundle from Selection")]    static void ExportResourceRGB2 ()    {        //Open the Save panel, get the path selected by the user        string path = Editorutility.savefilepanel ("Save Resource", "", "New Resource", " Assetbundle ");        if (path. Length! = 0)        {            //Select the object to save            object[] selection = selection.getfiltered (typeof (Object), Selectionmode.deepassets);            Packaged            Buildpipeline.buildassetbundle (selection.activeobject, Selection, Path, buildassetbundleoptions.collectdependencies | Buildassetbundleoptions.completeassets, buildtarget.standalonewindows);        }    }
At this point we will see the build Assetbundle from selection and build Scene below asset
3. Select the preset cube and execute the build Assetbundle from Selection. This will pop up a save box, name it Cube.unity3d (here for testing convenience, on the C drive. The actual project. We need to put them in webserver. Download updates for all clients)
4. Create a new scene scene1.unity, place several models on top, then save

5. Select the scene to add a function to package the scene in the previous ExportAssetBundles.cs script. Executes the Assets->build Scene. Save As Scene1.unity3d (here for testing convenience.) Also on the C-plate)

    [MenuItem ("Assets/save Scene")]    static void Exportscene ()    {          //Open Save panel to get user-selected path of        string path = Editorutility.savefilepanel ("Save Resource" , "", "New Resource", "Unity3d");        if (path. Length! = 0)        {            //Select the object to save            object[] selection = selection.getfiltered (typeof (Object), Selectionmode.deepassets);            String[] scenes = {"Assets/scene1.unity"};            Pack            Buildpipeline.buildplayer (scenes,path,buildtarget.standalonewindows, buildoptions.buildadditionalstreamedscenes);        }    }

Precautions
A.assetbundle can be saved with a assetbundle or Unity3d
B.buildassetbundle to be packaged separately based on different platforms, buildtarget the specified platform, assuming not specified, the default Webplayer
    • Load Assetbundle

We demonstrate how to load assetbundle in a simple code, including loading common asset and scenes.

using system;using unityengine;using System.Collections;    public class load:monobehaviour{private string Bundleurl = "File:///C:/cube.assetbundle";    private string Sceneurl = "File:///C:/scene1.unity3d";        void Start () {//bundleurl = "file//" +application.datapath+ "/cube.assetbundle";        Debug.Log (Bundleurl);    Startcoroutine (Downloadassetandscene ());        } IEnumerator Downloadassetandscene () {//download assetbundle, load cube using (WWW asset = new www (bundleurl))            {yield return asset;            Assetbundle bundle = Asset.assetbundle; Instantiate (bundle.            Load ("Cube")); Bundle.            Unload (FALSE);        Yield return new Waitforseconds (5); }//Download the scene. Load scene using (WWW scene = new www (sceneurl)) {yield return scene;            Assetbundle bundle = Scene.assetbundle;        Application.loadlevel ("Scene1"); }           }}

Precautions
A.loadfromcacheordownload can specify a version number. Assume that the local version number is new. Will not be read from server
B. Assuming that multiple resources are packaged together, we need to load specific resources through Bundle.load ()
C. Scripts that are mounted on the model can also be packaged together. However, it is guaranteed that the script will exist in the original folder, otherwise the load cannot be executed. I'll put it in a later chapter on how to update the script.


    • Assetbundle Dependency Relationship
Suppose a public object is dependent on multiple objects. When we were packing. There are two ways to choose. One of the more convenient is to package this common object into every object. This can be a lot of drawbacks: memory is wasted. The increase in public objects has changed. Each dependent object has to be packaged again.

Assetbundle provides packaging of dependencies.

We learn through a simple example

//enable cross-references for all trailing resource bundle files, Until we call Popassetdependenciesbuildpipeline.pushassetdependencies (); var options = Buildassetbundleoptions.collectdependencies |buildassetbundleoptions.completeassets;//All maybe the resources will share the contents of this resource bundle, It is up to you to ensure that the shared resource bundle loads Buildpipeline.buildassetbundle before other resources are loaded (Assetdatabase.loadmainassetatpath ("assets/artwork/        Lerpzuv.tif "), NULL," Shared.unity3d ", options); This file will share these resources, but perhaps the resource bundle will not be able to continue sharing it buildpipeline.pushassetdependencies (); Buildpipeline.buildassetbundle (Assetdatabase.loadmainassetatpath ("ASSETS/ARTWORK/LERPZ.FBX"), NULL, " Lerpz.unity3d ", options); Buildpipeline.popassetdependencies (); This file will share these resources, but perhaps the resource bundle will not be able to continue sharing it buildpipeline.pushassetdependencies (); Buildpipeline.buildassetbundle (Assetdatabase.loadmainassetatpath ("Assets/artwork/explosive guitex.prefab"), NULL , "Explosive.unity3d", options); Buildpipeline.popassetdependencies (); Buildpipeline.popassetdependencies (); 
We must ensure that the public object is loaded first when the program is loaded. Otherwise, it is only possible to manually join the individual objects after they have been successfully loaded into the program. More cumbersome. In the actual project, because it is team development. The dependencies between objects are generally more messy. It is best to set the relevant specification constraints in the development cycle. Easy to manage.
    • Summarize

This section of the content of the actual operation, the official documents and the Rain Pine Blog has been more specific introduction. Let's say we have a vague place. Be able to combine the document and then actually manipulate it.

Later chapters, I will spend a lot of time on the core content: incremental updates of resources. and a code program update .

    • Source

Http://pan.baidu.com/s/1i3BOAPn

    • References

1.http://www.xuanyusong.com/
2.http://game.ceeger.com/manual/downloadingassetbundles.html

Source: http://www.im286.com/thread-11924518-1-1.html

Assetbundle is a feature provided by Unity Pro. It is able to encapsulate multiple game objects or resource binaries into assetbundle, providing a convenient way to encapsulate and unpack them.

1. Presets

The Assetbundle can encapsulate the prefab. How convenient it is. And I strongly advise you to encapsulate prefab into assetbundle. Because prefab can be the game object on the body with the game components, game scripts, materials are packaged together.

When Assetbundle is downloaded from the server, it can be instantiate directly into the game.

Imagine that only the original binary resource file can be downloaded on the server, when the resource file is finished downloading, it is necessary to dynamically create the game object, and then dynamically bind the script to the game object, dynamic mapping to the game object and so on various dynamic operations.

。 So it is highly recommended to use PREFA, do not explain!

。!!



Other than that. I'm taking a sample, because the model has the potential to take a lot of animation files, then such a set of model resources may be multiple FBX files and several PNG map file material files. At this point I just need to put the original model into the prefab, it will include all the components of the model, even including its animation resources, stickers.

So for example, with what you see, mode is the model's prefab file. Then I just need to pack mode this preset into Assetbundle.

When I download the assetbundle on the server and load the game can be used directly, switch animation, change the map can be.



2. binary files

It's not all about using presets in Assetbundle. Assetbundle It is also able to encapsulate binary files directly inside. For example, pictures, sounds, text messages, and so on.



3. Scene files

A scene can be saved in unity. Scene will include all of this scene. Can you encapsulate the scene into Assetbundle? The answer is yes, but it can not be used on the mobile platform, because the mobile platform is unable to update the script, in other words, even if the script is bound in prefab, and then download Assetbundle, all the script will not run, the latter said the second clever use of the method.

4. Mobile Platform

Above Momo has introduced the use principle of assetbundle, we are talking about mobile platform.

The script cannot be updated to be the biggest injury on the mobile platform, which means that developers cannot bypass the App store and the online store such as Google Play to upgrade the app.

The only thing that can be done is to update the resources, give a sample example. In the game when processing version number upgrade, there will usually be a large version number and a small version number, the large version number is 2.0, 3.0 such a version number needs to be updated in AppStore. The major version is to upgrade the game script, and then when the minor version number, such as 2.0.1 or 2.0.2, just update the game's resources. You can complete the server through your own game. Download through Assetbundle on your own server and then adapt to the game.

Suppose you want to update the script, or you have to update the script, you can only update the big version on AppStore or Google Play.



The script cannot be updated on the mobile platform. So what about the prefab bound script? The script can be added to the prefab on any platform, and then packaged into Assetbundle. Just a little bit special on the mobile platform, for example, Test.cs this script into prefab. Finally, the program downloads this assetbundle through the server and will not be run when the script is loaded in project.

But suppose local project has Test.cs this script. Then unity will voluntarily bind the script to the downloaded prefab. And they run very well.

Assume that the script is not Test.cs in local project. Then the script on the prefab will never run. Sometimes we will write some public variables in the script, it is possible that different prefab bind the same script, only the public parameters in the inspector script are different. Don't worry about it. Assetbundle in the prefab is also no problem, so that only the large version of the script is not a problem, in the minor version of the only update game resources is a bit of a problem.

5. Mobile optimization

We said before that we could encapsulate a game object in the game as a assetbundle, and also be able to encapsulate the entire scene in the game as a assetbundle. But I think it is necessary to use the encapsulation scene skillfully. Since there must be a lot of common models in the scene, assuming that the memory and size are the size of the common model * n scenes, it is actually quite scary to think about it.

In fact, we can use it skillfully. Start by putting the common and private parts of the scene into unity and then baking the entire scene. When the scene is baked and the common model part is taken out, the scene simply retains the private model. It is also possible to make a tool to store the coordinates of the common model in the scene in the XML (each scene file will be the XML information for a common model), and finally to encapsulate the common model separately in the other assetbundle.



The assetbundle of each scene is provided on the server, and the assetbundle of the common model, the assetbundle of the general common model can be placed in resident memory (which may be used frequently, depending on the project) Assetbundle after the download is complete. Now the scene is loaded and the common model part is dynamically added to the scene based on the corresponding XML information in the scene, so that a scene is built.

6. Summary

Package all the resources in the game. For example, divide by type into five most interfaces, models, effects, sounds. Scene. Script.



Interface section:

Common Resource bundles (reusable resource bundles) and resource bundles (non-reusable resource bundles) unique to each interface are packaged in. assetbundle binary format using prefab.



Model part:

Categorize by role. Uniform use of prefab packaging into. Assetbundle binary format. The model section contains model files and animation files. Each model file corresponds to a set of animation files. (assuming that the model needs to be dressed up to provide a corresponding model and mapping), because the Unity4 redirection animation does not support dynamic loading. Therefore, it is not necessary to consider the model redirection animations of different sizes and genders.



Special effects section: Uniform use of prefab package into. Assetbundle binary format.

Voice part: Unified use Prefab to package into. Assetbundle binary format.

Scene part: The scene is a little different from the front. The scene needs to export the baking light information and can only bake a model that never moves on the scene, but these never-moving models are likely to be used in multiple scenarios at the same time, so after the scene is baked, the objects that are reused are removed. (performing the game in Dynamic onboarding) only preserves the model that never changes in the scene, as well as the baked light information. When you package a scene, the. Unity3d binary format is generated. It is different from the Assetbundle packaging method.

(in addition, JSON XML binaries can be considered for dynamic assembly scenarios).



Script section: Suppose that scripts are not executed (mobile platforms) on prefab, but unity has a knack for Assetbundle script packaging. The script on the prefab assumes that it will bind the local script on the Prefab object, and it will perform very well.

Prefab Packaging Tips: Prefab packaging itself is not a lot of space <=1kb but Prefab is able to correlate these five most "interfaces, models, effects, sounds, scenes, scripts" as well as in hierarchy view coordinates/zoom/rotate. This information will be very large after it is associated. Therefore, in order to avoid the waste of resources try to avoid prefab repeatedly associated.

A prefab the following can be associated with multiple game objects at the same time, here is a sample assuming your prefab to devolve a model its size may be 500k, in prefab to devolve 10 completely the same model its size may be 501k.

Assuming that prefab has two different models, it might be size 500k x 2, meaning prefab is irrelevant to the number of associations.

Encryption section: Assetbundle is capable of converting to byte arrays, and the client and server contracts a set of algorithms that decrypt a byte array to enable resource encryption.



Large Version Upgrade:

Unity's version number upgrade is actually a major upgrade to the script in the main program. Because all of the resources are Assetbundle and. Unity3d the way these resources are placed locally or unpacked by the server is the same, so theoretically our main package size can be very small, very good to set the amount of resources in the package Or put less resources on the server. At the time of execution the server should return the list of all assetbundle and. Unity3d resource files to the client.

Minor version number upgrade:

Minor version upgrade is also updated resources, due to the inability to update the script, at the time of landing on the server should be all assetbundle and the list of. Unity3d resource files back to the client.

There is another place to consider. Today, for example, the large version number is 2.0.0. The minor version number is already 2.0.5, and the user's phone is a 1.5.0 package. At this time the user should be forced to open the game to AppStore to download the large version of the 2.0.0, when the user completed the download after the game, at this time the server tells the client is now a small version of the 2.0.5, the client to download the corresponding small version number of all Assetbundle and. unity3d file address lists.



Incremental update: Theoretically incremental updates are feasible. Because Unity cannot update the script. So in the case of incremental updates, it is necessary to do so in code to be compatible with incremental updates.



Because assetbundle this piece of code is much more. I decided to write it in two separate articles. This article first says the principle, the next article says the code. You are welcome to discuss!

A few days ago I chatted with Unity Xin, and he told me that iOS was unable to execute when updating the script, but Android was able to execute when the update script. I tried it at home, but I didn't make it. Later I thought that even if I had succeeded in the project I do not intend to do so, because of the difference between Android and iOS is too much, and there is a unity store to deal with the implementation of the update script plugin Unitylua Everyone can go to research.

Assetbundle of Unity Resource Packaging

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.