Unity's Addressable addressable system -- change the resource loading method of Resources to Addressable loading -- actual combat (1)

1. Comparison of two resource loading methods

  1. Loading method:

    • Resources uses a synchronous loading method; when Resources loads resources, the application will be blocked until the resource loading is complete, which may cause the application to freeze or hang.
    • Addressables use asynchronous loading. This means that when using Unity to load resources using Addressables, the application can continue to run without stuttering or hanging.
  2. Dynamic loading:

    • Resources can only load resources from the project's Assets folder, and can only load resources at compile time.
    • Addressables can dynamically load resources at runtime, allowing for more flexible resource management.
  3. Resource management:

    • Resources can only be included in the installation package. If there are too many resources, the package size will increase.
    • Addressables can load resources from local or remote servers, and can perform flexible resource management and packaging through Addressables Group.
  4. Resource update:

    • Resources in Resources can only be updated by repackaging the application
    • Addressables can update resources in your application with simple resource updates or replacements without repackaging the entire application.

To sum up, Addressables is more flexible, efficient, and reliable than Resources, especially when dealing with a large number of or large resources. The asynchronous loading and flexible resource management functions of Addressables can greatly improve the performance and scalability of applications. However, when loading few or smaller resources, it is simpler and more convenient to use Resources.


Second, convert the Resource project to Addressables

2.1 Realize the logic

  • When a Resourcesresource within a folder is marked Addressableas , the system automatically moves it from Resourcesthe folder to Resources_movedthe new folder.
  • If there are multi-layer directories, the system will also retain them, and synchronize the directory structure Resources_movedcreated in and in the new folderResources
  • The marked resource addressable path (loading path Key) will also use the directory structure under the Resources directory.
  • The original loading code would Resources.Load<GameObject>("CZY/Czhenya.prefab")change fromAddressables.LoadAssetAsync<GameObject>("CZY/Czhenya.prefab")
  • public GameObject Czhenya;If the drag-and-drop assignment of such public variables is used in the project ,
    just modify the definition code to public AssetReference Czhenya;.
    Instantiation Instaniate()is changed toAssetRefName.InstantiateAsync();

It should be noted that the path key after the move is named after the directory under the Resources folder. When loading resources under the Resources folder, the path name is not case-sensitive, but the path key of AA needs to be case-sensitive.

Share a tool script:

The following script can be imported into the project, and then only need to modify in the project Resources.Loadto AAResources.Loadto complete the conversion of resource loading method.

using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

public class AAResources
{
    
    
    /// <summary>
    /// 可寻址资源加载
    ///     强制同步加载GameObject的基本用法
    /// </summary>
    /// <param name="pathKey">路径key</param>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static T Load<T>(string pathKey)
    {
    
    
        var op = Addressables.LoadAssetAsync<T>(pathKey);
        T go = op.WaitForCompletion();
        if (op.Status == AsyncOperationStatus.Failed)
        {
    
    
            Debug.LogError($"加载资源失败,路径:{
      
      pathKey},异常 {
      
      op.OperationException}");
            return default(T);
        }
        return go;
    }
}

Note: This method of synchronous loading is not supported on WebGL, but it is fine on other platforms.
insert image description here

The asynchronous writing method is as follows:

public async Task<T> LoadAssetAsync<T>(string pathKey) where T : UnityEngine.Object
{
    
    
    AsyncOperationHandle<T> handle = Addressables.LoadAssetAsync<T>(pathKey);
    await handle.Task;
    return handle.Result;
}

For other ways to load Addressable code, please refer to: Unity's Addressable Addressable System - Introduction to Code Loading - Advanced (1)


2.2 Operation steps

Changing the Unity resource loading method from Resources to Addressables requires the following steps:

  1. Install Addressablesthe package : Package ManagerInstall Addressablesthe package in Unity to use Addressablesrelated functions in the project.

  2. Configuration Addressables: Selected in Unity's menu bar Window -> Asset Management -> Addressables -> Groups, create a new Addressables Groupand add the required assets to it.

  3. Modify the code: modify the code that refers to Resourcesthe loading method, and use instead Addressablesto load resources. You can use Addressables.LoadAssetAsyncthe method to load resources asynchronously, or Addressables.LoadAssetthe method to load resources synchronously.


3. Precautions for using Addressables

When using Addressables to load resources, you need to pay attention to the life cycle and thread safety of resources. Here are some ways to deal with them:

  • Life cycle management: After using Addressables to load resources, you need to pay attention to the life cycle of resources to avoid resource leakage or accidental release. In general, you can use the AsyncOperationHandle.Release() method to release loaded resources. Before releasing resources, you need to ensure that all references have been released, otherwise resource leaks will result. If the resource is loaded multiple times, you need to call the Release() method to release the resource after all references are released.

  • Thread safety: When using Addressables to load resources, you need to pay attention to thread safety issues to avoid race conditions and other thread problems. Generally speaking, you can use asynchronous loading to avoid threading problems. If you need to access the asynchronously loaded results in the main thread, you can use Unity's coroutine (Coroutine) to handle asynchronous operations and access the asynchronously loaded results in the coroutine. In addition, it should be noted that in the callback function of asynchronous loading, do not directly modify the properties of the Unity object or call the Unity API, otherwise it will cause thread problems. If you need to modify the properties of the Unity object or call the Unity API in the callback function, you need to use Unity's main thread call (MainThreadDispatcher) to ensure thread safety.

  • Error handling: When using Addressables to load resources, you need to pay attention to error handling issues to avoid unhandled exceptions and error messages. Generally speaking, you can use the AsyncOperationHandle.OperationException property to get error information about asynchronous operations and handle the errors. If an exception occurs, a try-catch statement can be used to catch and handle the exception. It should be noted that in asynchronous operations, exceptions and error messages may be delayed until the asynchronous operation is completed before being captured and processed, so error handling needs to be performed after the asynchronous operation is completed.


Fourth, problems encountered in use

Error:

UnityEngine.AddressableAssets.InvalidKeyException: Exception of type ‘UnityEngine.AddressableAssets.InvalidKeyException’ was thrown., Key=Sound, Type=UnityEngine.AudioClip

Possible Causes:

  1. Check whether the specified group name is correct. It needs to be consistent with the group name in the Addressable system, including capitalization. You can view all group names and resources within them in the Addressables window.

  2. Check whether the specified resource exists in the specified group. It is necessary to ensure that the resource name is consistent with the name in the Addressable system, including capitalization.

  3. Check whether the specified resource type is correct, and it needs to be consistent with the actual resource type used. For example, if you need to load audio assets, you need to use Addressables.LoadAssetsAsync instead of Addressables.LoadAssetsAsync.

  4. If you use the label function of Addressables, you need to ensure that the specified label name is consistent with the actual label name, including capitalization.


Guess you like

Origin blog.csdn.net/Czhenya/article/details/130771779