To put you in context, in my Unity project I have a Master script and some generic functions to unify some functionalities.
My problem is, the generic function SpawnPrefab() has to know which prefab must spawn, which is provided by the GetPrefab() function defined in the generic type. So I made this approach to make it work:
First I created an interface like this:
interface IObject
{
GameObject GetPrefab();
}
class MyObject : IObject
{
public MyObject() { ... }
// The function that needs to be called inside the generic one
public GameObject GetPrefab() { ... }
}
And then, in Masterâs class:
static void SpawnRandom<T> where T : IObject, new()
{
T Instance = new T();
GameObject prefab = Instance.GetPrefab();
// Instantiates the prefab
...
}
Notice that I have to create a new generic object before calling the method. I thought in making the function GetPrefab static, but interfaces doesnât support them. So is it the correct way?
If not, my question is: whatâs the correct way to call the function GetPrefab()? Is it necessary to instantiate a T type in order to call the method?