So i have multiple data types like armorData, weaponData, itemData etc and wanted to make a generic resource load for them (they are scriptable Objects) but apperently T or system.Object is not convertable to UnityEngine.Object which is returned by the Resource.Load<>() method. So my question is, is there a way to make something like the code below work to get something like Resources.Load()
public class RessourceCollector<T>
{
public List<T> LoadPlayerResources(SaveDataStructure savedPlayerStats, List<string> savedCollection, string folderPath)
{
List<T> itemResources = new List<T>();
foreach (var armorSaveData in savedCollection)
{
T itemDataFromResources = LoadFromResource(folderPath, armorSaveData);
itemResources.Add(itemDataFromResources);
}
return itemResources;
}
public T LoadFromResource(string path, string itemName)
{
return Resources.Load<T>(Path.Combine(path, itemName));
}
}
I tried to use T or System. object/Object but nothing is convertable from the type UnityEngine.Object.
In your implementation, T
can be any type, while Resources.Load()
is restricted to UnityEngine.Object
types only.
This means that if you specify e.g. int
as your T
, the conversion from UnityEngine.Object
to int
is not possible. Thus the error.
You simply need to apply the same restriction to your generic parameter:
public class ResourceCollector<T> where T : UnityEngine.Object
Now you can only use UnityEngine.Object
and the types derived from it with ResourceCollector
, so the conversion is formally guaranteed.