Addressables resource management solution

1. What is Addressables

Unity Addressable Asset systemProvides a system that can grow with your project, replacing AssetBundle management resources without programming.
It has the function of self-assigning addresses, uses automatic addressing and loading when the time comes, automatically tracks local mobile resources and handles dependencies.

2. Import Addressables

1. Click 2. Search and import the plug- in 3. Unity requires a version after 2019Windows > PackageManager
Addressables

insert image description here

Note: In actual projects, it is recommended that you download Addressables.CNthe version.
insert image description here

3. Create Addressables Settings asset package management

1. ClickWindows > Asset Management > Addressables > Groups
insert image description here

2. Click the button in the pop-up Addressables Groupwindow to create. At this time, a group is created by default , and the AssetBundle is packaged according to ** ** by default . That is, multiple resources can be created in this interface, and resources can be stored, which will be generated by pressingCreate Addressables SettingsAddressablesAssetsData
Default Local Group (Default)AddressableGroup
GroupGroupAssetBundle.
insert image description here

3. A folder Addressable Settingswill also be generated in the project when it is created, and there are many setting files in it.AddressableAssetsData
insert image description here

4. Basic operation of resource collection Group (resource subcontracting)

1. In Addressables Group, you can click on the blank space to create a new one Group, which can be used as an out-of-package resource group (remote resource package)
insert image description here

2. RenameYou can modify Groupthe name by right-clicking
insert image description here

3. Then you can add resources by dragging or ticking Inspectoron the resources window Addressable.
insert image description here

4. When creating Group, a AssetGroupscorresponding YAMLformat file will also be generated to record resource content and guidance
insert image description here

5. Set up the remote resource package

1. Select Groupor the corresponding YAMLformat file, and you can see the build path Build Pathand loading path in the Inspector window . 2. You can change it to and , and you can see that the corresponding address below has also changed. In this way, when building and loading, it will go to the corresponding address above.Load Path.
insert image description here
RemoteBuildPathRemoteLoadPath
insert image description here

3. The address of the remote resource package can be clicked Addressables Groups> Manager Profilesor
insert image description here
in Windows > Asset Management > Addressables > Profiles the button
insert image description here

4. Open Addressables Profilesthe window to modify, as shown below:insert image description here

You can keep it unchanged for now, and this address will be used first.

6. How to pack

1. Let's execute it Build / New Build / Default Build Script, open Addressablethe resource pack, click and wait for a while, and there will be a Log prompt when it is completed.
insert image description here

2. The built local resource bundle will be stored Libraryin the specified address, as shown in the figure below:
insert image description here

3. The constructed remote resource project 根目录下will be stored in the specified address under ServerData, as shown in the figure below:
insert image description here

4. It is worth noting:
the local resources will be packaged in the package along with the APK.
However, remote resources will not be packaged in, and need to be placed in a specified location to load.

7. Loading method

7-1. Mono script specification and instantiation:

MonoScript public AssetReferencespecification and instantiation:
If we declare AssetReferencethe type instead of GameObjectthe type, then the scene directly depends on the preset, and this preset will be typed into the scene, but what we use here is that AssetReferencethe scene does not really depend on the Sphere preset, it is a weak reference.

public AssetReference spherePrefabRef;
void Start()
{
    
    
    spherePrefabRef.LoadAssetAsync<GameObject>().Completed += (obj) =>
    {
    
    
        // 预设
        GameObject spherePrefab = obj.Result;
        // 实例化
        GameObject sphereObj = Instantiate(spherePrefab);
    };
}

7-2. Instantiate the specified object directly

AssetReferenceInstantiate the specified object directly:
Similarly, the method AssetReferenceis also provided InstantiateAsyncto facilitate instantiation in one step:

spherePrefabRef.InstantiateAsync().Completed += (obj) =>
{
    
    
  // 已实例化的物体
  GameObject sphereObj = obj.Result;
};

7-3. Asynchronous callback loading

For example Addressables.LoadAssetAsync, listen to Completedthe callback, get the resource in the callback and then operate:
when we load the resource Group, we don't need to know which resource is in or where the resource is. Just need to know Addressable Name.
Use this as the basis for loading, for example:
insert image description here

Resource name as shown in the picture: Map1Bulid

Addressables.LoadAssetAsync<GameObject>("Map1Bulid").Completed += (handle) =>
{
    
    
    // 预设物体
    GameObject prefabObj = handle.Result;
    // 实例化
    GameObject cubeObj = Instantiate(prefabObj);
};

7-4. Asynchronous direct instantiation

AddressablesThe interface is also provided InstantiateAsyncto facilitate direct one-step instantiation, for example:

Addressables.InstantiateAsync("Map1Bulid").Completed += (handle) =>
{
    
    
    // 已实例化的物体
    GameObject cubeObj = handle.Result;
};

7-5. Ways to use async and await

Ways to use async, example:await

private async void InstantiateCube()
{
    
    
    // 虽然这里使用了Task,但并没有使用多线程
    GameObject prefabObj = await Addressables.LoadAssetAsync<GameObject>("Map1Bulid").Task;
    // 实例化
    GameObject cubeObj = Instantiate(prefabObj);
    // 也可直接使用InstantiateAsync方法
    // GameObject cubeObj = await Addressables.InstantiateAsync("Map1Bulid").Task;
}

7-6. Load the scene

Addressables.LoadSceneAsyncLoad the scene with

StartCoroutine(LoadScene());
private IEnumerator LoadScene()
{
    
    
    var sceneHandle = Addressables.LoadSceneAsync("NewScene");
    if (sceneHandle.Status == AsyncOperationStatus.Failed)
    {
    
    
        Debug.LogError("场景加载异常:" + sceneHandle.OperationException.ToString());
    }
    while (!sceneHandle.IsDone)
    {
    
    
        //监控进度0~1
        float progress = sceneHandle.PercentComplete;
        Debug.Log("加载进度:" + progress);
        yield return null;
    }
    Debug.Log("加载完毕:");
}

8. Loading environment simulation

There are three Addressables resource loading modes, as follows, the default is Use Asset Database (fastest)
insert image description here

1. Use Asset Database (fastest)

Resources can be loaded directly from AssetDatabase, avoiding the packaging process, so the loading speed is very fast. However, the profiler information obtained in this way is less, because the Addressables system does not need to package resources, so it will not generate AssetBundle cache information. Therefore, in the project development stage, it is recommended to use this non-packaging method to quickly load resources.

2. Simulate Groups (advanced)

In this mode, the operation of AssetBundle is simulated to obtain Profiler information similar to the packaging method. But unlike loading resources directly from AssetDatabase, it will simulate the cache information of AssetBundle, and then obtain Profiler data by analyzing this information. Because there is no need to package the Addressable resource bundle, there is no need to perform the Build operation. Therefore, this mode is fast and can obtain rich Profiler information, which is a good way for development and debugging.

3. Use Exising Build(requires built groups)

In this mode, it is still necessary to perform the Build operation to package resources into Addressable resource bundles. At runtime, the Addressables system will load the actual AssetBundle file and read resources according to the Load Path. Different from the previous two modes, this mode needs to package resources, so the Build operation needs to be executed first. If you do not build first, resources will not be loaded at runtime, causing the program to report an error. Therefore, this mode is suitable for the stage before the project is released or launched to ensure that the resources can be loaded correctly.

Nine, view the reference analysis panel

1. Click the menuProject > AddressableAssetsData > AddressableAssetSettings
insert image description here

2. InspectorFind Send Profiler Eventsand check in the window (different versions have different locations)
insert image description here

3. Then clickWindows > Asset Management > Addressables > Event Viewer
insert image description here

4. Open the ** Addressables Event Viewer** window, you can see information such as resource usage, number of references, etc.

In the analyzer, we can see the resources that our instantiated presets depend on, and we can also see information such as reference counts. Although we did not print out the AssetBundle package, we
simulated the effect of loading resources from the AssetBundle package, which is convenient for us to quickly analyze the loading strategy.
insert image description here

10. Hosting Service local server

This function can be used to simulate loading remote server resources in the local environment (use with caution in win11 system, unstable).
Click the menu Window / Asset Management / Addressables / Hosting, and then click Create / Local Hostingto create a local web server.
insert image description here

then checkEnable
insert image description here

In this way, we have opened a local server. The IP address is my local area network IP. I can access it through localhost. Note that the port number here is 55716.
We can see that it has carried out the two folder directories we mentioned above Hosting,
insert image description here

11. View duplicate resources

Tools > Window > Analyze1. Use this function to view repeatedly referenced resources, select Open ** Addressables Analyze** window in AddressablesGroup

2. Operate as shown below
insert image description here

3. After waiting for a period of time, you can view the resources repeatedly referenced in different packages, so that we can adjust the allocation and packaging conveniently

Eleven, WebGL platform issues

1. The editor cannot correctly read webgl resources when using external packages. 2. Remove the tick
under the resource groupUse Asset Bundle Cache
insert image description here

3. You still can’t see it in the editor, just publish webGl.

12. Unity version selection

1. Use several versions recommended by the official or it is easy to have some strange problems

13. Resource release

1. The following is the corresponding release method after the resource is loaded. Loaded , and unloaded Addressables.LoadAssetAsyncwith it . Example: //Get resource and instantiateAddressables.Release

Addressables.LoadAssetAsync<GameObject>("ModelHero0").Completed += (res) =>{
    
    
    ThisObj = res.Result;
    GameObject sphereObj = Instantiate(ThisObj);
};
//销毁和释放资源
GameObject.Destroy(ThisObj);
Addressables.Release(ThisObj);

Let's see that there is a reference count when loading and opening, and it will be cleared when destroyed
insert image description here

2. Scene loading and Addressables.LoadSceneAsyncunloadingAddressables.UnloadSceneAsync

3. Addressables.InstantiateAsyncThe instantiated ones can be used, and the supporting ones Addressables.ReleaseInstancecan be directly uninstalled and references cleared
. For example:

//加载并实例化
Addressables.InstantiateAsync("ModelHero0").Completed += (obj) =>
 {
    
     
 	ThisObj = obj.Result; 
 };
//卸载并清除引用
Addressables.ReleaseInstance(ThisObj);

Guess you like

Origin blog.csdn.net/ww1351646544/article/details/131461056