Cannot use Texture passed to a base class?
Alright guys, so I've got a GameObject class and I inherited it to my Player class. So I've done this in the constructor:
public Player(Vector2 position, Texture2D tex):base(position,tex)
{
}
Now, I have a Draw method, and I need the Texture to use the Draw method. But because I used the Texture from the GameObject class I can't use the texture in this method. What can I do about it? Leave a comment if you开发者_如何学编程 didn't understand anything.
Thanks in advance.
You should post a snippet of your GameObject class. Using my psychic abilities, I reckon your Texture object is declared as private in GameObject. Change it to protected like this:
class GameObject
{
protected Texture2D _texture;
public GameObject(Vector2 position, Texture2D tex)
{
...
_texture = tex;
}
}
class Player : GameObject
{
public Player(Vector2 position, Texture2D tex):base(position,tex)
{
}
public override void Draw(...)
{
// _texture should be accessible from here.
}
}
Read Access Modifiers to learn more about using private, protected, etc.
How is GameObject
storing tex
? The field it's being set to may not be accessible from the derived class Player
. Try changing it's access modified to protected
if this is the case.
Have you declared the _texture
member as protected?
public abstract class GameObject
{
protected Texture2D _texture;
public GameObject(Texture2D tex) {
_texture = tex;
}
public abstract void Draw();
}
public class Player : GameObject
{
public Player(Texture2D tex) : base (tex) { }
public override Draw()
{
//Do stuff with _texture.
}
}
精彩评论