Unity Addressables resource management system

Addressable Asset System

1. Background

  Before starting to introduce the Addressable system, let us first review several traditional resource loading methods:

  • Direct reference: Using direct reference is the simplest and fastest, but it cannot be loaded dynamically.
  • Resources resource management: All files in the Resources folder will be packaged into the installation package, regardless of whether the resources are used. This will cause the package body to be too large; Resources cannot be heated. Update resources; Resources has strict requirements on resource paths when loading resources.
  • AssetBundle resource management: Hot update is possible, but management is difficult.

2. Introduction to Addressable system

  The addressable asset system is a new resource management plug-in launched by Unity. The Addressable system is based on the Asset Bundle and provides rich resource management functions such as asynchronous loading, dependency management, and memory management. It also allows developers to implement remote resource updates more conveniently.

3. Advantages of Addressable system:

  • Quick iteration:
    Use Addressable to enter the rapid development stage in the early stage of development. No matter which resource management technology you like, you can quickly switch to the Addressable system. There is almost no need to modify the code.
  • Dependency Management:
    The system returns not only the requested content, but also all of its dependencies so that all meshes, shaders, animations, etc. are loaded before returning the content.
  • Memory management:
    Addressable can not only load resources, but also unload resources.
  • Content packaging:
    The Addressable system automatically manages all complex dependency connections, so even if the resources are moved or renamed, the system can still efficiently find the accurate dependencies for packaging. . When you need to move packaged resources from local to server, the Addressable system can easily do it. Compared with the traditional asset loading method (Resources/AssetBundle), the Addressable system has a complete visual editing window and memory management.

4. The difference between Addressable system and AssetBundle

  • The Addressable system only needs the address of the asset to load it from any location, while the AssetBundle needs to load the resource from the specified bundle package.
  • The Addressable system uses reference counting to automatically manage memory unloading, while AssetBundle requires developers to manage it manually.
  • The Addressable system automatically manages dependencies, while AssetBundle requires developers to manage dependencies themselves, which is more difficult to maintain.
  • By default, all loading operations of the addressable resource system are asynchronous operations, and event listeners can be added, while AssetBundle has synchronous and asynchronous loading.
    Insert image description here

Use of Addressable system

1. Installation

    For Unity 2018.2 and above, use PackageManager to install Addressables.
Insert image description here

2. Addressables management window

    Window > Asset Management > Addressables > Groups Enter the user interface
Insert image description here
Addressable settings:
    Resources are divided into Built In Data and LocalGroup by default ( Default) two groups, the former contains some built-in resources and cannot be changed, and the latter can add or delete resources.

  • Create: Create a new resource group. You can also right-click Create New Group > Packed Assets in the Addressables Group window to create a new resource group.
  • Profile: The role of Profile is mainly to specify several addresses that need to be used in the project. We can click Create->Profile in this window to create a Profile. Each Profile contains 4 default variables. We can also click Create->Variable to expand variables.
  • Tools:
    • Profiles: is used to set the range for the entire Addressable (configure the specific values ​​of the four paths). After that, you can select the path type for Build and Load of each group, based on the Profile. Select OK.
    • Labels: Add and delete labels Label.
    • Analyze: Analyze is a tool that collects information about the addressable layout of your project. In some cases, Analyze may take appropriate action to clean up the project's status. In other cases, Analyze is purely an information tool that allows you to make more informed decisions about your addressable layout. Insert image description here
    • Hosting Services: A resource service that comes with the Addressables system. You can specify a directory to store remote resources, and then update the resources by connecting to the server.
    • Event Viewer: can be used for monitoring and debugging. The premise is to check Send Message in the Inspect System Settings window (it is turned off by default because it consumes performance).
          Use the Addressables Event Viewer to monitor the reference counts of all resources operated by the Addressables system. In Unity select Window > Asset Management > Event Viewer.
          Note that the event viewer only cares about reference counting, not memory consumption. In each frame listed under the "Asset" column, you can see the following information for each resource:
          FPS: Frames per second.
          MonoHeap: The total amount of memory used.
          Event Counts: The total number of events per frame.
      Insert image description here
          You can click the left and right arrows to observe frame by frame, or click Current to jump to the latest frame. Press the + button to expand a row for more details.
          The information displayed in the event viewer is related to the game mode selected in the Play Mode Script. When using the Event Viewer, avoid using Use Asset Database mode because it does not take into account any dependencies between assets. Use Simulate Groups or Use Existing Build mode, but the latter is more suitable for the event viewer because it can more accurately monitor the reference count of the resource.
    • Check for Content Updata Restrictions: Update static resource group.
  • Play Mode Script:
    • Use Asset Database(fastest): Allows you to run the game quickly during gameplay. It loads Assets directly through the Asset Database, which results in fast iteration without the need for analyzers or assetBundle creation.
    • Simulate Groups(advanced): Analyze the contents of layouts and dependencies without creating assetBundles. Assets are loaded from assetDataBase via ResourceManager, pretending they are loaded via packages. To see when bundles are loaded or unloaded during a game, in the Addressables event viewer window Tools > Event Viewer
    • Use Exiting Build(requires built groups): is closest to a deployed application build, but it requires you to build the data as a separate step. If the Asset is not modified, this mode is the fastest because it does not process any data when entering Play mode. Content for this mode must be built in the Addressables group window (Window>Asset Management>Addressable>group>group) by selecting Build>New Build>Default Build Script, or using the AddressableAssetSettings.BuildPlayerContent() method in a game script.
  • Build:
    • New Build: When all resources are ready, click this to package.
    • Update a Previous Build: When resources are updated, click this to update the resource package.
    • Clear Build: Clear the resources that have been built. You need to build the game again to run the game again.

3. AddressableAssetSettings system settings

Insert image description here
Basic configuration of the Addressable system:

  • Disable Catalog Update On Startup: It is not checked by default. If it is not checked, then every time the AA system is initialized, the catalog file will be automatically updated. If it is checked, The catalog file will not be automatically updated, which means that resources will not be automatically updated. The initialization of the AA system will be initialized when any interface is called for the first time, or you can actively call Addressables.InitializeAsync() for initialization.
  • Build Remote Catalog: It is not checked by default. Only if it is checked, the catalog will be created in the specified directory. In the future, the client can download this catalog for comparison and update.
  • Build Path: The address where the resource is stored after packaging.
  • Load Path: Add source to the site.
  • Send Profiler Events: For debugging, it allows sending events to EventViewer when loading resources. You can use this tool to view resource usage
  • Log Runtime Exception: Outputs exceptions when loading resources. If an exception occurs when loading resources when it is turned on, it will be thrown directly. If it is turned off, we can also use the error returned when loading resources. handle to obtain exception information. At the same time, we can also add the macro ADDRESSABLES_LOG_ALL to the project to view more log information

4. Resource group settings

Insert image description here

  • Build Path: The address where the resource is stored after packaging.
  • Load Path: Add source to the site.
  • Advanced Options:
    • Asset Bundle Compression: The current compression method of .bundle files supports LZ4 and LZMA compression.
    • Include in Build: Whether to be packaged, the default is checked, if not checked, the current group will not be packaged.
    • Requset Timeout: Sets the number of seconds UnityWebRequest will attempt to abort after the timeout is exceeded. (Applies to remote resource bundles only)
    • Bundle Mode: Controls how bundles are packaged. PackTogether packages a group into a resource package; Pack Separately packages each resource into a package, and Pack Together By Label packages the same resources of Label into a resource package.
  • Content Update Restriction:
    • Update Restriciton:
      • Cannot Change Post Release: Static Group cannot be modified after release. It can only be incrementally updated through Check for Content Updata Restrictions to create a new resource group.
      • Can Change Post Release: Non-static Group is allowed to be modified after release, and will be overwritten when updated.

5. Mark resources

Insert image description here
    There are two ways to mark resources as addressable. After installing the addressable resource package, you can mark it in the properties panel or drag it to a designated group in the management window. On the resource's Properties window, click the Address checkbox and set a unique identifier for the resource.

Note: If the assets we mark are in the Resources folder, the Addressable system will prompt you to move the assets out of the Resources folder.
Insert image description here

6. Resource packaging

    Configure resource grouping, set Play Mode Script as needed, and then package and test through Build > New Build > Default Build Script.
    Local resource packaging path: Library/com.unity.addressables/StreamingAssetsCopy/aa/Android/
    Remote resource packaging path : ServerData/Android/
Insert image description here
    At the same time, .hash and .json files will be generated in the remote directory. The .hash file only contains the hash value of a catalog file. When used to detect catalog updates for customer orders, the hash value is compared to determine whether there is a catalog update. The json file contains the hash value and address of each Ab package.
    Use Build > Update a previous Build When updating the resource package, you need to select a bin file (android environment as an example, Anroid/.bin). This bin file records the differences between all Ab packages. Dependency and grouping information, the Addressable system manages dependencies through this bin file.

7. Load resources

    Use AssetReference to load resources:

[SerializeField] private AssetReference m_AssetReference; 
    private  void Start() {
    
     
        m_AssetReference.LoadAssetAsync<GameObject>(); 
    }

    Use Addressables to load a single resource:

 private void OnResLoadAsset(string key) 
    {
    
     
        Addressables.LoadAssetAsync<GameObject>(key).Completed += OnCompleteLoad;
    } 
    private void OnCompleteLoad(AsyncOperationHandle<GameObject> asyncOperationHandle) 
    {
    
     
        GameObject go = GameObject.Instantiate(asyncOperationHandle.Result); 
    }
    private void OnResInstantiate(string key) 
    {
    
     
        Addressables.InstantiateAsync(key); 
    }

     Load multiple resources:

private void OnResLoadAsset(string key,string lable) 
    {
    
     
        Addressables.LoadAssetsAsync<Texture2D>(new List<object> {
    
     key, lable }, null, 
            Addressables.MergeMode.Intersection).Completed += OnCompleteLoadAssets; 
    } 
    private void OnCompleteLoadAssets(AsyncOperationHandle<IList<Texture2D>> asyncOperationHandle) 
    {
    
     
        //DebugTools.Log(asyncOperationHandle.Result.Count); 
    }

Note: The third parameter, MergeMode, searches for the merge mode of resources. Take the incoming parameter as new List{key,label} as an example.

  • When using Node or UseFirst, the resource queried by the first key will be taken.
  • When Union is used, take the union
  • When Intersection, get the intersection

Summary:
(1) When loading resources, if the type specified by the resource to be loaded is inconsistent with the resource type, and the Addressable system cannot find the resource, an exception will be thrown and the resource cannot be loaded. , Prerequisite: Send Profiler Events is checked in the system settings.
(2) Using tag management, the address and tag of the same resource can be the same. When there are multiple resources with the same tag, the Addressable system will return the first resource that meets the conditions.
(3) If the address name of the resource is the same as the label of the next resource, the return will still be the first resource. The Addressable system will compare the address and label of the resource. If they are both different, it will continue. Search Down

8. Update resource package

    After the hot update resource package is modified, the resources need to be repackaged
    Check for Content Update Restrictions: For a static resource group, it is an Update Restriction The property is Cannot Change Post Release value. After clicking, a pop-up will pop up to select the bin file generated by the previously packaged resource group. Click "Apply Changes" to apply the changes. The added or modified resources will be moved to the new Content Update group. Insert image description here
    Update a Previous Build: When the dynamic resource group is updated, to perform this operation, you also need to select the bin file, and the system will automatically generate a new AB package.
Insert image description here

9. Hot update code and solutions

    core code

 public IEnumerator CheckForContentUpdate(List<object> keys)
 {
    
    
     for (int index = 0; index < keys.Count; index++)
     {
    
    
         AsyncOperationHandle<long> DownloadSize = Addressables.GetDownloadSizeAsync(keys[index]);
         yield return DownloadSize;
         if (DownloadSize.Result <= 0)
         {
    
    
             Debug.Log("[Addressable]:不需要更新的资源标签:" + keys[index]);
             keys.Remove(keys[index]);
         }
         else
         {
    
    
             m_TotalSize += DownloadSize.Result / Mathf.Pow(1024, 2);
         }
     }
     m_DownloadDependencies = Addressables.DownloadDependenciesAsync(keys, Addressables.MergeMode.Union, false);
     yield return m_DownloadDependencies;
}
  • Option 1:
        Get updated resource tags from the server.

Note: When dynamic resources are updated, old resources will be overwritten. There is a resource in the dynamic resource group that needs to be updated. During hot update, the entire resource group will be downloaded
, so it is reasonable. It is very important to divide resources into groups to reduce repeated downloads and packaging granularity (multiple resources require the same materials, textures, etc.).

  • Option 2:
        Use the officially provided Addressables.CheckForCatalogUpdates() method to check the catalog and obtain the catalog that needs to be updated.
  • Option 3:
        Violently obtain all Keys, use the official Addressables.GetDownloadSizeAsync(Key) to check whether the resource needs to be updated, and obtain all Key values ​​that need to be updated.
        Resource update specific implementation:
            Use the officially provided Addressables.GetDownloadSizeAsync(Key) method to obtain all resource addresses or tag sets that need to be updated, and then use Addressables.DownloadDependenciesAsync (Key, Addressables.MergeMode.Union, false) Download updated resources.

10. Automatic grouping of resources

    When there are too many resources that need to be managed in the project, the method of checking Addressable or dragging and dropping is obviously not suitable. Therefore, a method needs to be implemented to mark all resources in a certain folder as addressable resources.
    Create a new menu in the editing state, create an asset file, and configure the resource folders that need to be marked. Multiple resources can be marked at the same time. The configuration is as follows:
Insert image description here

public static void AutoSetGroup(string groupName, string lableName, string assetPath, bool isSimplied = false) 
{
    
     
    var set = AddressableAssetSettingsDefaultObject.Settings; 
    AddressableAssetGroup Group = set.FindGroup(groupName); 
    if (Group == null) 
    {
    
     
        Group = set.CreateGroup(groupName, false, false, false, new List<AddressableAssetGroupSchema> 
            {
    
     set.DefaultGroup.Schemas[0], set.DefaultGroup.Schemas[1]}, typeof(SchemaType)); 
    } 
    string Guid = AssetDatabase.AssetPathToGUID(assetPath);  //获取指定路径下资源的 GUID(全局唯一标识符)
    AddressableAssetEntry asset = set.CreateOrMoveEntry(Guid, Group); 
    if (isSimplied) 
    {
    
     
         asset.address = Path.GetFileNameWithoutExtension(assetPath); 
    } 
    else 
    {
    
     
         asset.address = assetPath; 
    } 
    asset.SetLabel(lableName, true, true); 
}

    Specific ideas:
        According to the folder path, obtain the path information of all resources under the folder, call the add group interface, check whether the current group exists, if not, create it AddressableAssetGroup type group objects, set the default state, use AssetDatabase.AssetPathToGUID to obtain the GUID of the current path resource, and create an AddressableAssetEntry object through AddressableAssetSettingsDefaultObject.Settings.CreateOrMoveEntry(). After addressable is checked, simplify the resource address and setting label.

11. Memory management

Resource loading
    Addressables.LoadAssetAsync(); single resource
    Addressables.LoadAssetsAsync(); multiple resources
    Addressables.LoadSceneAsync(); Scene loading
    GamoeObject instantiation loading
    Addressables.InstantiateAsync(); Instantiation loading
    GameObject.Instantiate(); Unity provides instantiation methods
Resource unloading
    Addressables.UnloadSceneAsync(); Scene unloading
    Addressables .Release(); release the resource, the parameter is the resource or AsyncOperationHandle handle
    Addressables.ReleaseInstance(); destroy the instance created by the Addressable system

Note: Another difference between Addressables.InstantiateAsync() and other loading calls is that there is an optional trackHandle parameter. When set to false, resources must be released through the AsyncOperationHandle handle, and resources can no longer be released through AsyncOperationHandle.Result. .

Reference counting issue: Resource unloading, both manual and automatic.
    Manual uninstallation, Addressable system loading and unloading resources exist in pairs, use the Addrsssables.Release() or Addressables.ReleaseInstance() method to unload resources and reduce the reference count. When a resource's reference count reaches 0, the resource is ready to be unloaded and the reference counts of all dependencies are decremented.
    Automatically uninstalls, allowing automatic cleanup when the scene containing it is closed.
Uninstallation problem
    If the instance passed in using Addressables.ReleaseInstance() is not created by the Addressables system API, or the instance is created through a handle, the system will detect it. and returns false to indicate that the method cannot release the specified instance. In this case, the instance is not destroyed.
Addressables.LoadAsset() and Addressables.InstantiateAsync() Discussion
    Addressables.InstantiateAsync() has some overhead associated with it, so if you need to instantiate it in every frame If you want to instantiate the same object hundreds of times, consider loading it through the Addressables.LoadAsset() method and then instantiating it through GameObject.Instantiate(). The disadvantage is that the Addressables system does not know how many instances you have created, which can cause memory issues if not managed properly. For example, a Prefab that references an incorrectly loaded or unloaded texture can cause rendering issues (or worse). This type of problem is difficult to track down because you may not trigger memory unloading immediately. ​
Clear memory
    A resource that is no longer referenced does not necessarily mean that the resource asset has been unloaded. A common application scenario involves multiple resources contained in a resource package. For example:
     You have three resources ("tree", "tank", "cow") in the same resource pack ("stuff").
     When "tree" is loaded, the ref-count of "tree" +1, and the ref-count of "thing" +1.
     Later, when "tank" loads, both "tree" and "tank" have a ref-count of 1, and the "stuff" package has a ref-count of 2.
     If you release the "tree", its ref-count will become 0.
    In this example, the "tree" resource is not actually unloaded. You can load a resource pack or parts of it, but you cannot partially unload a resource pack. None of the assets will be uninstalled until the package itself is completely uninstalled. The exception to this rule is Resources.UnloadUnusedAssets, executing this method in the above scenario will cause the tree to be unloaded. Because the Addressables system does not recognize these events, it only reflects the ref-counts of Addressables (which does not fully reflect what exists in memory). Note that if you choose to use Resources.UnloadUnusedAssets, this is a very slow operation and should only be called on a screen that does not display any game content (such as a loading screen).

12. Addressable packaging granularity

    When we use the Addressable system, we need to consider: How many Groups are needed? What resources are placed in this Group? Is the packaging method Pack Together or Pack Together By Label or Pack Separately? Obviously, this is the same as using Assetbundle and requires developers to plan it themselves. This is not because Addressable is not powerful enough, but because it is related to the specific project, and the situation of each project is different.

Guess you like

Origin blog.csdn.net/weixin_42186644/article/details/120175299