Search code examples
c#unity-game-engineinterfacecastingtyping

How to Instantiate GameObject from Interface list


So, i have List<ITower>.

If I try to do:

var a = new List<ITower> {new DotBehaviour(), new RndBehaviour()};

foreach (var tower in a)
    Instantiate(tower);

I get:

The type 'ITower' must be convertible to 'UnityEngine.Object' in order to use it as parameter 'T' in the generic method 'T UnityEngine.Object.Instantiate(T)'

So I would be happy if:

a) you tell me how to do this OR

b) how to make return method in interface, that would return prefab associated with GameObject I want to instantiate. (Idk how to do this because of strong typing of C#, but I don't want to use dynamic)


Solution

  • There is a default interface method implemetation in the newest version of C#, but I don't know if unity implemented it yet. If they did you potentially could define a method in you interface and return the prefab you want to insantiate. Something like:

    GameObject GetPrefab()
    {
        return Resources.Load("Path/To/My/Prefab");
    }
    

    then you would call Instantiate(tower.GetPrefab()); instead of Instantiate(tower);.

    If you Unity version does not have a support for default interface methods, then you would have to implement the GetPrfab method in relevant scripts