- Home /
[C#] Calling a method of a child class on a parent object
Hey guys,
currently I am programming a game where the player has to steer a block through a tile-based level.
I have different kinds of "Tiles", e.g. "StartTiles", "NormalTiles" or "EndTiles". Therefore I have established a hirachy where Tile is the parent class and the other Tile types are children of that class, expanding it e.g. with an ID for a certain color that Tile should show.
In my game I want to set the ID for the color of the Tile to the current color of the block after it moved ontop of it.
However as there are different Tiles I use the parent class "Tile" as a parameter and then check exactly, what kind of Tile the block is ontop of. This means I am sure that this certain "Tile" is e.g. a "NormalTile".
The "NormalTile" class has a "SetColor()" method that is not present in the parent class. This is why I cannot call it in line 9, because this method is not in the Tile class.
Is there a fancy way to solve this issue without adding a specific virtual or abstract "SetColor()" method to the parent class "Tile"?
Here is the Code from the PlayerMovement script.
public void AfterMove(Tile newPosTile)
{
switch (newPosTile.GetID())
{
case TileManager.NormalTile:
{
if (color > 0)
{
newPosTile.SetColor(ColorManager.colors[color]);
}
} break;
default:
{
} break;
}
//canMove = true;
}
Answer by sacredgeometry · Mar 30, 2020 at 06:04 PM
How about you use interfaces instead of inheritance? Then all your tiles which are moveable would implement the AfterMove method defined in your IMovableTile interface and you can call that method on any IMovableTile without caring exactly how it works but knowing that it can.
Either that or maybe composition. I would tend to stay away from inheritance unless you are absolutely sure its what you want as its quite prone to becoming inflexible.
I agree on using an interface.
Sticking with your current method you could use the “is” operator.
It checks the type of an object and casts it for you.
if (newPosTile is NormalTile tile)
{
tile.SetColor(blah);
}