Search code examples
c#unity-game-enginegridtile

C# How to instantiate inherited objects via a static method?


I'm currently working on an isometric tile-based game. Currently, I have a grid with tiles and those objects contain data about their position, type and various objects(like trees) that can be placed on top of them.

I created an abstract TileObject class and there is another class called Tree which inherites from TileObject. My goal is to have a static function which is responsible for creating these TileObjects without using constructor.

I've tried this with Generics too (even using the Activator class) but didn't seem to work. My thoughts would be generics, system.type, typeof but I'm unable to put these all together.

public abstract class TileObject
{
    protected TileObject() { }

    public Tile Parent { get; set; }
    public string ObjectType { get; set; }

    public static TileObject CreateObject(string objName, Tile parent)
    {

    }
}

public class Tree : TileObject
{

}

This solution could work in my opinion but it seems so hardcoded

public static TileObject CreateObject(string objName, Tile parent)
{
    TileObject x;
    if(objName == "Tree")
        x = new Tree();
    else if(objName == "Chair")
        ...
}

Solution

  • One solution could be generics !

    Here is an example :

    
    public static TileObject CreateObject<T>(Tile parent) where T : TileObject, new()
    {
        TileObject x = new T();
    }
    

    Take a look at where T : TileObject, new()

    What it means is your type T will be a TileObject, so you don't even have to take care of the type.