Component.cs
public abstract class Component
//abstract to it has to be inherited and any child will be
//forced to use the Draw & Update class
{
public abstract void Draw(GameTime gameTime, SpriteBatch spriteBatch);
public abstract void Update(GameTime gameTime);
}
Button.cs
public abstract class Button : Component
//abstract to it has to be inherited and any child will be
//forced to use the Draw & Update class
{
// #region Fields
private MouseState _currentMouse;
private SpriteFont _font;
private MouseState _previousMouse;
private Texture2D _texture;
// #endregion
public event EventHandler Click;
public Color TextColour { get; set; }
public Vector2 Position { get; set; }
public Rectangle Rectangle
{
get
{
return new Rectangle((int)Position.X, (int)Position.Y, _texture.Width, _texture.Height);
}
}
public string Text { get; set; }
public Button(Texture2D texture, SpriteFont font)
{
_texture = texture;
_font = font;
TextColour = Color.White;
}
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
var colour = Color.White;
spriteBatch.Draw(_texture, Rectangle, colour);
if (!string.IsNullOrEmpty(Text))
{
var x = (Rectangle.X (Rectangle.Width / 2)) - (_font.MeasureString(Text).X / 2);
var y = (Rectangle.Y (Rectangle.Height / 2)) - (_font.MeasureString(Text).Y / 2);
//center the font within the button
spriteBatch.DrawString(_font, Text, new Vector2(x, y), TextColour);
}
}
public override void Update(GameTime gameTime)
{
_previousMouse = _currentMouse;
_currentMouse = Mouse.GetState();
//sets position of the mouse to actual current position
if (_currentMouse.LeftButton == ButtonState.Released & _previousMouse.LeftButton == ButtonState.Pressed)
{
Click?.Invoke(this, new EventArgs());
//if click event handler is != null ....use it
}
}
}
I have these classes set up to register a button press on my game.
Within game1.cs I tried to add the following to load content.
_spriteBatch = new SpriteBatch(GraphicsDevice);
var randomButton = new Button(Content.Load<Texture2D>("Controls/Button"), Content.Load<SpriteFont>("Fonts/Font"))
{
};
When implementing this I get error code CS0144 "Cannot create an instance or abstract type or interface 'Button'"
at the top of game1 I am using namespace.Controls as Button.cs is located in a folder called Controls. Any assistance or advice on this would be welcomed.
CodePudding user response:
Why is Button abstract
?, abstract types cannot be initialized with the new keyword, instead their constructors are considered abstract and a derived type should call base()
to it, consider not abstracting the class Button if possible (possible means: if you have any abstract member, than it is not possible, else, yes it is).