I'm a little new to C#, but I have a fairly extensive background in programming.
What I'm trying to do: Define different MapTiles for a game. I've defined the base MapTile class like this:
public class MapTile
{
public Texture2D texture;
public Rectangle mapRectangle;
public MapTile(Rectangle rectangle)
{
this.mapRectangle = rectangle;
}
}
I then define a subclass GrassTile like this:
class GrassTile : MapTile
{
new Texture2D texture = Main.GrassTileTexture;
new public Rectangle mapRectangle;
public GrassTile(Rectangle rectangle) : base(rectangle)
{
this.mapRectangle = rectangle;
}
}
In my Main class I'm creating a new maptile like this:
Maptile testTile;
testTile = new GrassTile(new Rectangle(0, 0, 50, 50);
However, when I try to render this testTile, its texture ends up being null. My code works fine if I define the texture inside MapTile, so it has nothing to do with my previous implementation of it.
So how can I get GrassTile to be able to modify MapTile's member variable texture? or get my main class to recognize GrassTile's texture instead of MapTile's I fiddled with interfaces as well, but I can't declare interface member variables. Is there something else to C# inheritance that I don't get yet?
Thanks in advance
Child class will inherit members of parent class. You don't need to specify them. Also it's better to use properties rather than public fields.
public class MapTile
{
public Texture2D Texture { get; set; }
public Rectangle MapRectangle { get; set; }
public MapTile(Rectangle rectangle)
{
MapRectangle = rectangle;
}
}
public class GrassTile : MapTile
{
public GrassTile(Rectangle rectangle) : base(rectangle)
{
Texture = Main.GrassTileTexture;
}
}
You have a little bit of a syntax confusion. "new" keyword can either be used as an operator to instantiate something, as you do in your main, or as a modifier to members to hide inherited members and that's what you're doing in your GrassTile. You're essentially redefining your members there. Correct version might be:
class GrassTile : MapTile
{
public GrassTile(Rectangle rectangle) : base(rectangle)
{
texture = Main.GrassTileTexture;
}
}
as your rectangle gets set in the base constructor anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With