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.
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.
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.
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.