我试图创建一个按钮,当我单击它时,它将游戏状态更改为正在玩,然后调用将要玩游戏的所有内容,但是我无法获得返回游戏状态的方法。
private GameState Playbutton_Click(object sender, EventArgs e)
{
GameState CurrentState = GameState.playing;
return CurrentState;
}
我得到的错误是 “ Game1.GameState Game1.Playbutton_Click(object,EventArgs)”具有错误的返回类型
编辑:
在游戏1:
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
enum GameState
{
playing,
menu,
over
}
GameState CurrentState = GameState.playing;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
GameState CurrentState = GameState.playing;
Playbutton = new Button(Content.Load<Texture2D>("button"), Content.Load<SpriteFont>("Font"))
{
position = new Vector2(690, 500),
Text = ("Play")
};
Quitbutton = new Button(Content.Load<Texture2D>("button"), Content.Load<SpriteFont>("Font"))
{
position = new Vector2(690, 800),
Text = ("Quit")
};
Playbutton.Click += Playbutton_Click;
Quitbutton.Click += Quitbutton_Click;
components = new List<Component>()
{
Playbutton,
Quitbutton
};
private void Quitbutton_Click(object sender, EventArgs e)
{
Exit();
}
private void Playbutton_Click(object sender, EventArgs e)
{
GameState CurrentState = GameState.playing;
}
按钮类:
private MouseState _currentMouse;
private SpriteFont _font;
private bool _isHovering;
private MouseState _previousMouse;
private Texture2D _texture;
public event EventHandler Click;
public bool Clicked { get; private set; }
public Color PenColour { 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;
PenColour = Color.Black;
}
public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
var colour = Color.White;
if (_isHovering)
colour = Color.Gray;
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);
spriteBatch.DrawString(_font, Text, new Vector2(x, y), PenColour);
}
}
public override void Update(GameTime gameTime)
{
_previousMouse = _currentMouse;
_currentMouse = Mouse.GetState();
var mouseRectangle = new Rectangle(_currentMouse.X, _currentMouse.Y, 1, 1);
_isHovering = false;
if (mouseRectangle.Intersects(Rectangle))
{
_isHovering = true;
if (_currentMouse.LeftButton == ButtonState.Released && _previousMouse.LeftButton == ButtonState.Pressed)
{
Click?.Invoke(this, new EventArgs());
}
}
}
}
答案 0 :(得分:2)
事件处理程序的签名几乎总是:
void SomethingHappened(object sender, EventArgs e)
通过方法订阅此事件时,必须遵循其定义的方法签名,包括使用相同的返回类型,在本例中为void
。
在这种情况下,您可以返回某些内容的唯一方法是创建一个变量,以后可以访问该变量并将其分配给它,或者(如果定义了事件处理程序,则)重新定义方法签名以返回{{1} }。
根据您的链接代码,您似乎在修复中有正确的想法。按照惯例,您不应从EventHandler返回任何内容,而应拥有一个可以在触发事件时设置并稍后再访问它的成员变量:
GameState