Unity Addressable Quick Use

Note: Addressable is referred to as Aa in the following

Reasons to use Aa

  1. Dynamic loading can be achieved using Aa, where dynamic loading refers to loading a resource when we need it. The resources here can be prefabs, pictures, sound effects, etc.
    The advantage of doing this is: Avoid loading all resources at once, occupying unnecessary memory, avoiding slow loading of mobile phone resources, heating of the mobile phone, and freezing.
  2. Hot update of resources can be done. Note that the resources here do not include code. This part will be discussed in detail later.

Install Aa

Please add a picture description
Please add a picture description
The .CN suffix is ​​the encrypted version, but it seems that I have seen an article saying that there are a large number of GCs, and I haven’t checked it yet.
Here the version without suffix is ​​used first.

Use Aa

1. Create Aa

insert image description here
Please add a picture description

2. Add resources that need to be dynamically loaded

Method 1: Select the resource and check Aa in the Inspector
insert image description here
Method 2: Select the resource and drag it directly to the Aa panel
insert image description here

Precautions

After adding resources that need to be dynamically loaded, you can right-click to simplify the name , where the name is the parameter required in the following code .
insert image description here

3. Load with code

method one:

      //使用LoadAssetAsync方法
        Addressables.LoadAssetAsync<GameObject>("Alpha@Alpha").Completed += (handle) =>
        {
    
    
            // 预设物体
            GameObject result = handle.Result;
            // 实例化
            GameObject alpha = Instantiate(result);
            alpha.transform.position = new Vector3(-4, 0, 0);
        };

        //使用InstantiateAsync方法
        Addressables.InstantiateAsync("Alpha@Alpha").Completed += (handle) =>
        {
    
    
            // 已实例化的物体
            GameObject alpha = handle.Result;
            alpha.transform.position = new Vector3(-2, 0, 0);
        };

Both LoadAssetAsync and InstantiateAsync can be used to load Aa resources. The difference between the two is that InstantiateAsync directly instantiates it for you , eliminating the need for the Instantiate process in LoadAssetAsync .

Method Two

The method of using async and await

    private async void InstantiateBetaObj()
    {
    
    
        //使用LoadAssetAsync方法
        GameObject betaPrefabObj = await Addressables.LoadAssetAsync<GameObject>("Beta@Beta").Task;
        GameObject betaObj1 = Instantiate(betaPrefabObj);
        betaObj1.transform.position = new Vector3(2, 0, 0);

        //使用InstantiateAsync方法
        GameObject betaObj2 = await Addressables.InstantiateAsync("Beta@Beta").Task;
        betaObj2.transform.position = new Vector3(4, 0, 0);
    }

Note: When testing, you need to add async in the function header , don't just copy the content of the function body.

method three

Declare the AssetReference type . The AssetReference type is a weak reference type and will not be included in the package body . If the GameObject type is declared, it will be included in the package body.

 //先声明类型
 public AssetReference newPrefabRef;
        newPrefabRef.LoadAssetAsync<GameObject>().Completed += (obj) =>
        {
    
    
            // 预设
            GameObject result = obj.Result;
            // 实例化
            GameObject newPreObj = Instantiate(result);
            newPreObj.transform.position = new Vector3(0.9f, 0, 0);
        };

        newPrefabRef.InstantiateAsync().Completed += (obj) =>
        {
    
    
            // 已实例化的物体
            GameObject newPreObj = obj.Result;
            newPreObj.transform.position = new Vector3(-0.9f, 0, 0);
        };

Here we are using the declared type of LoadAssetAsync, InstantiateAsync to create.

So far, the simple use process of Aa has been introduced. Other content is described below.


How Aa is loaded

insert image description here
Use Asset Database : You don’t need to build the Addressable resource package to use code loading (you can choose this in development).
Simulate Groups (advanced) : It can be loaded by code without building an Addressable resource pack. However, the loading of Aa can be simulated and the data can be statistically analyzed to facilitate our quick analysis ( detailed steps are below ).
Use Exising Build : You need to execute the Build first to print the Addressable resource bundle , which will load the real AssetBundle file and read the resource according to the Load Path. If you do not build first, an error will be reported at runtime. You can also use the analyzer to see resource dependencies and reference counts.

View Statistical Citations

  1. Check Send Profiler Events in AddressableAssetSetting
    insert image description here
  2. open window
    insert image description here

Construction of Aa outside the inclusion

We can also build Aa resources outside the package and load the resource package through the network.

create group

insert image description here
After right-clicking the created group, you can rename it. I changed it to RemoteAssets here.

Specify the BuildPath and LoadPath of Aa outside the package

Find the path in the figure below, select the configuration file with the same name as that created in the previous step, and modify BuildPaht in the Inspector, LoadPath is RemoteBuildPath, RemoteLoadPath.
( The AddressableAssetsData in the path will be created after installing Aa )
insert image description here

Modify the specific path of BuildPath and LoadPaht

Note the difference between this and the above. The above content is to specify whether the path of Aa is local or remote .
And the content here is to modify the local or remote specific path . The opening method is as follows:
insert image description here
Here we use the real environment test instead of the Hosting provided by Addressable.
insert image description here
When we get here, we try to build.
insert image description here
After the build is successful, we can see that there is an additional ServerData folder under the project path, and the contents inside are the resources outside the package we created.
insert image description here

start testing

Now let's test it out!
First, we need to modify the Play Mode Script to Use Existing Build mode .
The purpose of changing the mode to UseExisting Build here is to simulate the real environment. If we choose the other two modes, we can run successfully without putting resources on the server, so the test is not accurate.
Of course, we are here just to test whether loading through the network can load the Aa resources we need. In actual development, there is no need to modify to Use Exiting Build mode .

code part

Regardless of whether the Aa resource is outside the package or inside the package, the loading method is the same.

  1. We create an empty RawImage object
    insert image description here
  2. Reference to the RawImage object
public RawImage headIcon;
  1. Load the image and assign it to RawImage
  Addressables.LoadAssetAsync<Texture2D>("pansen").Completed += (obj) =>
        {
    
    
            // 图片
            Texture2D tex2D = obj.Result;
            headIcon.texture = tex2D;
            headIcon.GetComponent<RectTransform>().sizeDelta = new Vector2(tex2D.width, tex2D.height);
        };

Put the Aa resource we created before on the server

Put the resources under ServerData/StandaloneWindows64 we created above on the server. I won't demonstrate it here.

start operation

After clicking play, you can see the effect.
insert image description here

test

Now I want to know, is this resource downloaded from the Internet?

  1. Let's delete the resources on the server first.
  2. Delete locally cached resources. Use the Everything tool to search for the hash value of the Aa resource, pay attention to the hash value, not the name of the entire Aa resource, otherwise the resources cached on our computer will not be found.
    insert image description here
  3. Delete the Aa resources built locally, that is, the resources under ServerData/StandaloneWindows64

Now let's run it again. It is found that the following error will be reported:
insert image description here

Grain fineness modification

When we build, we package according to Group as the particle by default. What if we want to modify it to use a single file as the particle?
Let's add another picture in RemoteAssets first, and then build it.
insert image description here
You can see that there is only one .bundle file.
insert image description here

Take a single file as granularity

Select the remote configuration file, and change the Bundle Mode to Pack Separately in the Inspector . Let
insert image description here
's try Build again:
insert image description here
you can see that two .bundles are output. Corresponding to each image resource respectively.

Use the Label label as the granularity

The particle size on the top is too fine, sometimes we don't want to divide it so finely. At this point we can use Label as the granularity.

new label

  1. open window
    insert image description here
  2. add tag. Press the plus sign to add, here I added two: Audio, Texture.
    insert image description here

set tab

We add a sound resource to RemoteAssets and set tags for all resources. As follows:
insert image description here

Modify the packaging method

Select our remote resource configuration file and modify the Bundle Mode in the Inspector to Pack Together By Label
insert image description here

result

After Build, you can see the .bundle with Label as the granularity.
insert image description here

Multiple Label tags for one resource

We can also put multiple tags on a resource, as follows:
insert image description here
The result after Build is as follows:
insert image description here
Note : In the above results, there is only the image "pansen" in the .bundle in the middle, and only "gouxiong" in the .bundle with the texture name in the end this picture. In other words, although we have set the Label "Texttrue" for both images, they will not include each other when they are built.

Use code to load the same Label tag resource

Although when packaging above, the two resources containing the texture tag were packaged separately. But what we get here is that as long as it contains the same tag, it will be loaded .

  1. Declare AssetLabelReference type
public AssetLabelReference textureLabel;
  1. Set as Texture tag
    insert image description here

  2. code acquisition

         //加载同个Label标签资源
        Addressables.LoadAssetsAsync<Texture2D>(textureLabel, (texture) =>
        {
    
    
            Debug.Log("加载资源: " + texture.name);
        });
  1. As a result,
    both pansen and gouxiong are output.
    insert image description here

hot update resource

Now I need to replace the avatar in the box in the picture below
insert image description here
with the following one:
insert image description here

Open Build Remote Catalog

As shown below, select AddressableAssetSettings and check Build Remote Catalog. Select the values ​​specified by BuildPath and LocalPath.
insert image description here

rebuild

After rebuilding, you can see that there are more .hash and .json files starting with catalog in the output directory . These two files will only appear after we checked Build Remote Catalog above.
insert image description here
For the convenience of testing, I only have one "pansen" picture under RemoteAssets here, so there is only one .bundle file.

Precautions

Note that if resources need to be hot updated, then make sure that the resources to be replaced have two files of the catalog. That is to say, if I didn't check Build Remote Catalog at the beginning , then Build. At this time, it is no problem to load pictures remotely and dynamically, but it is not possible to replace pictures with hot update , because we need to compare the two files of the catalog. Then look down.

Test resource loading

Drag the files built above to the server. Then use the code to test whether it can be loaded normally. The code still uses the above and will not be repeated:

 public RawImage headIcon;
        Addressables.LoadAssetAsync<Texture2D>("pansen").Completed += (obj) =>
        {
    
    
            // 图片
            Texture2D tex2D = obj.Result;
            headIcon.texture = tex2D;
            headIcon.GetComponent<RectTransform>().sizeDelta = new Vector2(tex2D.width, tex2D.height);
        };

The result is as follows, here it means that we loaded successfully:
insert image description here

replace resource

Replace the previously used "pansen" resource with the following
insert image description here

Build: Update a Previous Build

Note that this is not the Build – New Build – Default Build Script we often use above , but use the following:
insert image description here
After clicking, a file box will pop up, allowing you to select the .bin file. Because I am testing on a computer, I choose window.

Step1:
insert image description here
Step2:
insert image description here
Double-click to select the .bin file. A new .bundle and two files of the modified catalog will appear in BuildPaht.
insert image description here

test

Note that the two files of the modified catalog and the newly added .bundle file need to be uploaded here . Only uploading .bundle will not take effect.
Here's what re-runs do:
insert image description here
If your results don't change, it's probably a local file cache. According to the above method of using Everything to find the cache, delete the previous cache. At the same time, delete the previous .bundle under ServerData/StandaloneWindow.

Aa resource release

Load code:

      Addressables.LoadAssetAsync<Texture2D>("pansen").Completed += (obj) =>
        {
    
    
            // 图片
            tex2D = obj.Result;
            headIcon.texture = tex2D;
            headIcon.GetComponent<RectTransform>().sizeDelta = new Vector2(tex2D.width, tex2D.height);
        };

Release code:
Note the need to use Addressables.Release .

    public void ReleaseAaAsset()
    {
    
    
        //释放资源
        if (tex2D != null)
        {
    
    
            Addressables.Release(tex2D);
        }

        //销毁RawImage
        Destroy(headIcon.gameObject);
    }

You can open EventViewr to view the changes:

Before release:
insert image description here
After release:
There is no "pansen" resource after release.
insert image description here

Article content reference: link

Guess you like

Origin blog.csdn.net/qq_28644183/article/details/125368191