Getting InvalidKeyException but Key shows on Addressables.ResourceLocators

Hi there! I’m trying to steer away from using Resoures in my game and trying to implement Addressables, but just can’t get it to work.

I keep getting this error in the Editor

Exception encountered in operation CompletedOperation, status=Failed, result= : Exception of type 'UnityEngine.AddressableAssets.InvalidKeyException' was thrown., Key=Enemy, Type=Enemy

when doing this

Addressables.LoadAssetAsync<Enemy>("Enemy");

but I have it there

And I built the Default build script

I even tried this:

{
foreach (var key in l.Keys)
{
Debug.Log(key);
}
}```

And I DO see Enemy in the console
![6388701--712077--Screen Shot 2020-10-06 at 10.39.17 AM.png|2004x1328](upload://r5bJz9wmRwNQJ7wRFTjnRNJVn4w.png) 

So I don't know what else to do! Am I missing a step?

Thank you!

Wow, thank you so much @ProtoTerminator for this answer on an unrelated issue: Difference between InstantiateAsync and LoadAssetAsync

It looks like the error is completely misleading. The problem was not that it was not finding the key, but the type was wrong.

This is the original code I was trying to port:

Enemy enemy = Instantiate(enemyPrefab, enemiesContainer.transform.position, enemiesContainer.transform.rotation);```

And this is what I was trying (which led to the error in the first post): 

```Enemy enemyPrefab = await Addressables.LoadAssetAsync<Enemy>(enemyType.toStringValue()).Task;
Enemy enemy = Instantiate(enemyPrefab, enemiesContainer.transform.position, enemiesContainer.transform.rotation);```

Now I changed it to this:

```GameObject enemyPrefab = await Addressables.LoadAssetAsync<GameObject>(enemyType.toStringValue()).Task;
Enemy enemy = Instantiate(enemyPrefab, enemiesContainer.transform.position, enemiesContainer.transform.rotation).GetComponent<Enemy>();```

And everything is working fine now. By the way, if there is a better way to do this, please let me know.

Changing the post tag to Bug in hopes the exception can be fixed to better address the issue.
2 Likes

+1 for a better exception in this instance. UnexpectedTypeException or something similar… Needed to find this thread to figure out why a valid key was yielding an InvalidKeyException.

3 Likes