Difference between InstantiateAsync and LoadAssetAsync

What is the difference between the two methods?

I have some code to use an asset reference to add to a list.

public static async Task CreateAssetAddToList<T>(AssetReference reference, List<T> completedObjs)
        where T : Object
    {
        completedObjs.Add(await reference.InstantiateAsync().Task as T);
    }

When using InstantiateAsync, the code throws the following error:

Exception encountered in operation UnityEngine.ResourceManagement.ResourceManager+CompletedOperation`1[UnityEngine.GameObject], result='', status='Failed': Exception of type 'UnityEngine.AddressableAssets.InvalidKeyException' was thrown., Key=2d691567d7cd748d3877d24f47306701
UnityEngine.AddressableAssets.AssetReference:InstantiateAsync(Transform, Boolean)
<CreateAssetAddToList>d__0`1:MoveNext() (at Assets/8_Addressable/LoadAddressables.cs:113)
System.Runtime.CompilerServices.AsyncTaskMethodBuilder:Start(<CreateAssetAddToList>d__0`1&)
AddressableLoader:CreateAssetAddToList(AssetReference, List`1)
<Start>d__9:MoveNext() (at Assets/8_Addressable/LoadAddressables.cs:38)
System.Runtime.CompilerServices.AsyncTaskMethodBuilder:SetResult()
<InitAsset>d__4`1:MoveNext() (at Assets/8_Addressable/LoadAddressables.cs:193)
UnityEngine.UnitySynchronizationContext:ExecuteTasks() (at /Users/builduser/buildslave/unity/build/Runtime/Export/Scripting/UnitySynchronizationContext.cs:104)

However if I instead use LoadAssetAsync like below, it works completely fine:

public static async Task CreateAssetAddToList<T>(AssetReference reference, List<T> completedObjs)
        where T : Object
    {
        completedObjs.Add(await reference.LoadAssetAsync<T>().Task);
    }

What is the difference?

The difference is LoadAssetAsync loads it as an asset and doesn’t instantiate it in the scene. InstantiateAsync instantiates it directly in the scene.

The difference in your code is you are using LoadAssetAsync but InstantiateAsync without and trying to cast to T. I’ve noticed that if you try to load or instantiate without the exact type that it is, it throws a key exception (makes no sense, and something Addressables should report better). Hence why your InstantiateAsync without is throwing an error.

3 Likes