I’m not sure if this is a bug, but the ResourceType property in IResourceLocation doesn’t return the same type as what is returned from the asset when it is a Texture2D and when the generic type parameter is UnityEngine.Object.
Marking a sprite as an addressable marks both a Sprite and Texture2D, which I get. But my expectation is that one IResourceLocation would return a Sprite while the other would return a Texture2D, but the following code indicates that they both return Texture2D.
var objectHandle = Addressables.LoadAssetAsync<Object>(resourceLocation);
objectHandle.Completed += (asset) =>
{
//returns Sprite
Debug.Log(resourceLocation.ResourceType);
//returns Texture 2D
Debug.Log(asset.Result.GetType());
};
The upshot is that, if I want to create a dictionary of generic assets to keep in memory using UnityEngine.Object, I have to check whether the IResourceLocation.ResourceType == typeof(Sprite) and use a type-specific overload for LoadAssetAsync like so:
private static Dictionary<string, Object> myDictOfAssets = new Dictionary<string, Object>();
private static void RetrieveGameAssets(IList<IResourceLocation> locations)
{
foreach (IResourceLocation resourceLocation in locations)
{
if (resourceLocation.ResourceType == typeof(Texture2D))
{
continue;
}
else if (resourceLocation.ResourceType == typeof(Sprite))
{
var objectHandle = Addressables.LoadAssetAsync<Sprite>(resourceLocation);
objectHandle.Completed += (asset) =>
{
string dictKey = resourceLocation.PrimaryKey + resourceLocation.ResourceType.ToString();
Object dictValue = (Object) asset.Result;
myDictOfAssets.Add(dictKey, dictValue);
};
}
else
{
var objectHandle = Addressables.LoadAssetAsync<Object>(resourceLocation);
objectHandle.Completed += (asset) =>
{
string dictKey = resourceLocation.PrimaryKey + resourceLocation.ResourceType.ToString();
Object assetValue = asset.Result;
myDictOfAssets.Add(dictKey, assetValue);
};
}
}
}
This solution works, but making conditional statements for Sprites and Texture2D obviously feels bad.
Am I missing something here? Every example I have seen uses independent LoadAssetAsync examples for specific types, but I really don’t want to have a Dictionary for every asset type.
Curious if someone has a better solution.
Thanks,