How to get asset type from AssetReference

Hi,
I would like to store sprites or gameobjects in AssetReference field.

But I don’t know how to get right asset type before loading it.

Debug.Log(problemSceneObject.AssetReference)
returns something like this:
[e8f2657930ee6604ba8aff0d41b468a7]tatrovka (UnityEngine.Texture2D)

Debug.Log(problemSceneObject.AssetReference.Asset.GetType());
returns null if game run first time
returns tatrovka (UnityEngine.Sprite) after first time

As I don’t have non generic way how to load asset. I’m curious how you handle that.

Thanks
Peter

Unfortunately, AssetReference just holds a GUID, and counts on invoker to provide the asset type via LoadAsset(). However you can use the type specific version of AssetReference, like
AssetReferenceGameObject,
AssetReferenceTexture,
AssetReferenceTexture2D,
AssetReferenceTexture3D
AssetReferenceSprite.

If you want something more generic way to detect asset type, load IResourceLocation via address first, then check the ResourceType property.

Hi,
please do you have an example how to get address from asset reference and basic working with iresourcelocation?

Or in newest update we may use LoadAsset approach?
I have tried to search through forum but it looks like old ways do not work now with new api.

Thanks
Peter

Argh I was using an old package of Addressables . So not it makes more sense as I see new API. So researching further…

Some async-await style example,

var locations = await Addressables.LoadResourceLocationsAsync(address).Task;
if (locations == null)
    return;
foreach (var loc in locations)
{
    var asset;
    if (loc.ResourceType == typeof(Sprite))
        asset = await Addressables.LoadAssetAsync<Sprite>(loc).Task;
    else if (loc.ResourceType == typeof(GameObject))
        asset = await Addressables.LoadAssetAsync<GameObject>(loc).Task;
    if (asset != null)
        // do something with the asset.
}

The for-loop is necessary, since for texture, LoadResourceLocationsAsync will return two entries, one for raw texture, one for sprite.

There’s no easy way to invoke Addressables.LoadAssetAsync with loc.ResourceType, so have to manually detecting asset type as above. See more in https://forum.unity.com/threads/how-to-load-asset-with-iresourcelocation-and-resourcetype-reflection.697574/

As you seen, this generic approach is a bit complicated, depends on your usage. If you really like to use AssetReference and only stores gameobject and sprite, then you can also make two lists, one for AssetReferenceGameObject, one for AssetReferenceSprite. That will simplify your loader.

3 Likes