Unity Assetbundles and Resources guidelines (i)

Source: Internet
Author: User

The content of this article is mainly translated from the following article

https://unity3d.com/cn/learn/tutorials/topics/best-practices/guide-assetbundles-and-resources?playlist= 30089 A Guide to Assetbundles and Resources

In order to eliminate some ambiguity, the proper noun in the article is directly in English words, such as assets, Resource, Object

This article is about in-depth discussion of assets and resource management in the Unity engine, which is divided into four sections:

    1. Analyze the underlying details of unity serialization assets and handling references between assets.
    2. Discusses the built-in resources API.
    3. The basis of Assetbundle is discussed on the basis of the first part. For example, loading assetsbundles and loading assets from Assetbundles.
    4. Discuss the application mode of Assetbundle. For example, assign a value to Assetbundle assets and load assets from Assetbundle and discuss some common pitfalls that developers encounter when using Assetbundle.

Note: The vocabulary objects and assets mentioned in this article are somewhat different from the naming conventions of the Unity public API. For example, this article says that objects is called assets in some APIs, For example, Assetbundle.loadasset and resources.unloadunusedassets. Files called assets in this article have very few APIs that are publicly available, even if they are exposed as build-related APIs. Like Assetdatabase and Buildpipeline. In these APIs they are more files.

Part I.: Assets,objects and serialization

This section discusses the internal details of the referential relationship between the editor and runtime Unity engine serialization and maintenance objects. The difference between objects and assets is also discussed. With this understanding, you can effectively add and unload assets in unity. Proper assets management is the key to ensuring less load time and less memory consumption.

1.1 Inside Assets and Objects

To properly manage your data in unity, you need to understand unity recognition (Identifiles) and serialization (serializes) data.

First, let's distinguish between assets and unityengine.objects:

A assets is a storage file stored in a assets folder in a unity project. such as arts and sciences files, material files and FBX files are assets. Some assets contain data in Unity's native format. Some assets need to be processed in a cost-effective format. such as FBX files.

Unityengine.object is a set of serialized data that describes a special instance of a resource (instance). The resource available in the Unity engine can be of various types, such as grids, sprites, sound clips, animated segments, and so on. All objects are subclasses of Unityengine.object. Although most of the objects types are built-in. But there are two special types:

    1. Scriptableobject provides developers with a way to easily customize their data types. This type can be serialized and deserialized by Unity and can be edited in the View window.
    2. Monobehaviour provides a package that connects to the Momoscript. A monoscript is an internal data type that unity can use to keep a reference to a script class in an assembly and namespace.

Assets and objects are a one-to-many connection, and a given asset file contains a single or multiple objects.

1.2 A reference between object

All unitengine.objects can cause other objects. Other objects may be present in the same asset file and can be imported from other asset files. For example, a material object often has a reference to one or more map objects. These map objects are typically imported from one or more map asset files.

When serialized, these references contain two parts of the data: the GUID of the file and the local ID. The file GUID is used to determine where the asset file is stored. The local ID is used to determine each object inside the asset file, because each asset file may contain more than one objects.

The file GUID is stored inside the. meta file. When unity first imported a asset, unity generated a. meta file for the asset in the same directory.

We can use the text editor to see what we've said. Create a new Unity project, display the meta file in the editor settings and set the serialization asset to text format. Import a map in the project and create a material to assign the decal to the material. Create a cube in the scene and assign the material to the cube. Then open the material's. Meta with a text editor, and you can see that there is a row at the top that flags the GUID. This defines the GUID of the asset file. Using a text editor to open the material file, you can find the local ID, for example, looks like this

---! U!21 & 2100000

Material:

Serializedversion:3

... more data ...

Above 2100000 is the local ID of the materail. If the GUID of the asset file to which the Materail object belongs is "ABCEDFG", then the material object can be uniquely tagged with the GUID "ABCDEFG" and the local ID "2100000".

1.3 Why do I need the file GUID and local ID?

Why are GUIDs and local IDs necessary? The answer is for robustness and elasticity.

The GUID abstracts the file location. As long as a GUID can be associated with a file, the file location becomes irrelevant, so the file in unity can be moved freely without updating the objects that references the file.

Because a asset file can contain multiple object resources, the local ID needs to be used to differentiate each individual object.

If the GUID of the asset file is missing, all objects referencing the asset file are lost. Therefore, it is important that the. meta file be saved in the same directory as the asset file. Unity will regenerate the meta file that was deleted or misplaced.

The Unity Editor maintains a collection of paths with a GUID map. When a asset is loaded into the project, a new mapping is added. If editor finds a meta file missing when running, as long as the asset path does not change. Unity ensures that the same GUID is generated.

If unity is not running and the meta file is missing, or the asset path changes and the meta file is not moved together. All references to the asset inside the objects will be lost.

1.4 Composite Assets and importers

The previously mentioned non-native asset types can be imported into unity, which is done through the asset importer. Although it is usually called automatically, it can still be called through ASSETIMPORTERAPI. For example, when importing texture asset, TEXTUREIMPORTERAPI provides a way to set it up externally.

The result of the import process is one or more objects. These are externally visible in the form of unityeditor within the parent asset. For example, when a map is imported as a sprite atlas, there are several sprites below. Each object shares a file GUID because they are stored in the same asset file, and the sprites are distinguished by their local IDs.

Import processing will process the source asset into the appropriate format for the target platform set by editor. This processing can protect very heavy operations, such as arts and sciences compression. The efficiency will be very low if the editor is to operate every time it is opened. So unity caches the processing results in the Library directory. In particular, there is a directory in the library/metadata/ directory that consists of the preceding 2 bits of the GUID.

1.5 Serialization and instantiation

Although the GUID and local ID are robust, the GUID is relatively slow and therefore needs to be optimized at run time. Unity maintains a cache that converts GUIDs and localid into a unique integer called the instance ID. The cache maintains the source location defined by this instance ID and GUID and local ID, as well as the in-memory object (if any). This allows object to maintain reference to each other. The instance ID enables you to quickly find an object that has already been loaded. If the target object has not yet been loaded, the asset location can be located by GUID and local ID, and unity can load the object in time.

Initially, the instance ID cache initializes all the items that need to be compiled by objects (such as scene references), and all objects of the resource directory. Running the newly imported resource is appended with the objects loaded from Assetbundles. An entry for an instance ID is removed from the cache only when it is useless. For example, Assebundle was unloaded.

1.6 monoscripts

It is important to recognize that Monobehaviour has a reference to Monoscript. Monoscript only contains some information that locates a script and does not contain the executable code of the class: assembly name, class name, and namespace.

When compiling a project, unity collects all the scripts and compiles them into an assembly. Unity compiles an assembly for each language, and an assembly for the plugins directory. For example, C # scripts outside the plugins directory are compiled into Assembly-csharp.dll. Compiled into Assembly-csharp-firstpass.dll under the plugin directory.

The assembly is included in the final application. Monoscript is a reference to this. When the program starts running, all assemblies are loaded.

That's why Assetbundle doesn't really contain executable code.

1.7 Resource life cycle

The objects is loaded and unloaded in memory. To reduce load times and manage application memory, we need to understand the life cycle of his resources.

There is an automatic and an explicit load of object. When the instance ID and object are not associated to the surface when the object is not loaded into memory, the object is loaded automatically when the asset,unity can be located. Scripts can explicitly load objects, such as either they can be created or they can be loaded through the resource API (Assetbundle.loadasset).

When loaded, Unity resolves the reference to the GUID and local ID to the instance ID.

An instance ID of an object is first referenced to the following two conditions when it is loaded:

    1. The object referenced by the instance ID is not currently loaded.
    2. The GUID and local ID associated with the instance ID are already registered in the cache.

If the GUID and local ID do not have an instance ID, or if the instance ID refers to an incorrect GUID and local ID, the reference is preserved, but object cannot be loaded. A missing will appear at this time. The missing object is visible depending on the type, such as if the texture is missing.

Objects will be uninstalled in the following situations:

    1. Objects is automatically uninstalled when the unused asset is cleaned up. such as scene switching or code calls to the Resource.unloadunusedassets method will trigger cleanup of resources. This will only unload objects that are not referenced: There is no script variable reference to this object, and no other active state of objects references this object.
    2. Objects loaded from the resource folder can be explicitly unloaded through the Resource.unloadasset method. The object instance ID is still there after uninstallation, and if there are script variables or other objects that have references after unloading, the object will be reloaded immediately.
    3. When you call Assetbundle.unload (True), the objects loaded from Assetbundle is unloaded immediately. Any reference to the object will show a loss. Any reference unload object inside the script throws a null reference error.

If Assetbundle.unload (false) is called, the objects loaded from Assetbundle will be destroyed. But unity will be the GUID and the local ID associated with the instance ID are invalidated. If the remaining objects are unloaded, they cannot be loaded again.

1.8 Loading deep-level objects

When serializing hierarchical objects (such as prefabricated objects), the entire hierarchy is fully serialized. That is, each object and component is serialized into the data in a single sequence, which also affects the loading and instantiation times.

When creating the Gameobject hierarchy, CPU time is mainly spent in the following areas:

    1. Read resource data (from memory or other gameobject)
    2. Set up a new transform parent-child relationship
    3. Examples of new gameobject and components
    4. Wake-up Gameobject and components

Whether it's cloning or reading from memory, the last three takes time, but the read time increases linearly as the level increases.

Now on the platform, it is faster to store the device from memory or not. In the future, as storage media changes,

can also be very different, desktop PC will be mobile devices to fast. If you are loading from a slow device. The time to read the data is much more than the instantiation time, so the performance bottleneck is on the I/O.

When serializing a prefabricated object, all gameobject and component data are serialized

Even if the object is copied. For example, a screen UI has 30 identical elements, and the 30 same elements are serialized 30 times. Generates a lot of two-level data. When loaded, the data is then read from disk and converted to the newly instantiated object. File reads occupy the main time consumed when instantiating large prefabricated objects.

Once instantiated, it is much faster to clone one than to read the load from disk.

Note: unity5.4 modifies the representation of the transform object in memory, and the child transform of each root transform are in compact arrangement in memory. When you need an instance of a gameobject that is immediately a child of another object, consider using the new Gameobject.instantiate overloaded method, which takes a parent parameter and increases the speed back by 5%-10%.

Unity Assetbundles and Resources guidelines (i)

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.