【Unity】【Addressable】ラベルに対応する全アセットのResourceLocationを取得する

Unity の Addressable アセットシステムで、ラベルに対応する全アセットの ResourceLocation を取得する方法についてまとめました。

Unity2020.3.40
Addressables 1.18.19

ラベルからResourceLocationを取得する

ラベルから各アセットの ResourceLocation を取得するには、以下のようにAddressables.LoadResourceLocationsAsync を使用します。

using System.Collections;
using UnityEngine;
using UnityEngine.AddressableAssets;

public sealed class Example : MonoBehaviour
{
    private IEnumerator Test()
    {
        // LoadResourceLocationsAsyncにラベルを渡す
        var locationsHandle = Addressables.LoadResourceLocationsAsync("SomeLabel", typeof(GameObject));

        if (!locationsHandle.IsDone)
            yield return locationsHandle;

        // 含まれるアセットのResourceLocationを取得
        var locations = locationsHandle.Result;

        foreach (var location in locations)
        {
            // IResourceLocationからPrimaryKeyを取得したり
            Debug.Log(location.PrimaryKey);

            // IResourceLocationを使って個別にロードしたり
            yield return Addressables.LoadAssetAsync<GameObject>(location);
        }

        // 不要になったらちゃんとRelease(他のAsyncOperationHandleと同様)
        Addressables.Release(locationsHandle);
    }
}

なお ResourceLocation の取得からそれを使った処理をまとめて一つの AsyncOperationHandle に結合したい場合には、Addressables.ResourceManager.CreateChainOperation を使うことができます。
これについては以下の記事にまとめていますので、必要に応じて参照してください。

light11.hatenadiary.com

参考

https://docs.unity3d.com/Packages/com.unity.addressables@1.21/manual/GetRuntimeAddress.html