I´m making this game but I´ve run into a problem with the structures. I´ve made a class called Structure and other classes like Traps, Shelter, Fireplace inherits from this class. The tiles in the game have their own class(Tile) and have a list of Structures on that tile. I can succesfully build structures on tiles which are included in the list. The problem comes when I try to acces the functions from classes like Traps etc. it won´t work. I can only use the functions from the base class Structure.
List in Tile:
class Tile
{
public List<Structure> Structures = new List<Structure>();
}
How I build a Trap or other building:
bool anyFireplace = Bundle.map.tile[Bundle.player.X, Bundle.player.Y].Structures.OfType<Shelter>().Any();
if (!anyFireplace)
{
woodlogsCost = 4;
if (Bundle.player.Woodlogs - woodlogsCost >= 0)
{
Bundle.map.tile[Bundle.player.X, Bundle.player.Y].Structures.Add(new Shelter(Bundle.player.X, Bundle.player.Y));
Bundle.player.Woodlogs -= woodlogsCost;
}
}
When I draw the Structures (here is where my problem is, note the comments)
foreach (Structure s in Bundle.map.tile[x, y].Structures)
{
if (s is Fireplace)
{
//This is the function from base class Strucure
s.ColorBody(g, 10, x - minx, y - miny, 0, Brushes.Firebrick);
// The function that I wan´t to use but can´t be used
//s.ColorBody(g, x - minx, y - miny);
}
if (s is Shelter)
{
s.ColorBody(g, 10, x - minx, y - miny, 1, Brushes.ForestGreen);
}
if (s is Sleepingplace)
{
s.ColorBody(g, 10, x - minx, y - miny, 2, Brushes.Brown);
}
if (s is Trap)
{
s.ColorBody(g, 10, x - minx, y - miny, 3, Brushes.Silver);
}
if (s is Barricade)
{
s.ColorBody(g, 10, x - minx, y - miny, 4, Brushes.DarkOliveGreen);
}
}
Soo… I wonder how do I access the functions I wan´t to use?
To the computer,
sis only aStructure. If you want to call a specific method that only theFireplaceclass has but the abstract classStructuredoes not have (e.g.Fireplaceclass might have aBurnWood()method that wouldn’t make sense for aStructureto have), then you want to let the computer know that thisStructureis actually also aFireplace(for example). So you could do this by casting; for example:or
See this post on the difference between casting and using the
asoperator.