3

I'm creating a menu system for my game, and am trying to make the buttons so that on creation, I can pass a set of instructions (or function) to execute on a click event.

I have a function called ChangeScreen, which takes an enum parameter, Screen, and I'd like to be able to pass this function into the button listen event, like so (pseudo-code incoming):

menuButtons.Add( new MenuButton(ChangeScreen(Screen.Settings), texture, hovertexture, position) );

I'd then enumerate over menuButtons and call each button's Update and Draw methods. I love this idea, it seems relatively more efficient than assigning each MenuButton to it's own variable, rather than writing if statements to check each button specifically.

That's not the only use case I'd like though. If it is possible, I would love to be able to pass in a method like:

menuButtons.Add( new MenuButton(new Method() { variableToSet = 1; }, texture, hovertexture, position) );

I tried using Action but I just don't understand how to go about doing this correctly. Is at all possible, or is there a similar solution?

zuddsy
  • 2,455
  • 2
  • 13
  • 19

1 Answers1

1

So, I figured out a solution that's as close as I can get.

In my MenuButton object, I have

public delegate void ButtonEventHandler(object sender, EventArgs e);
public event ButtonEventHandler onClick;

When I want to check for a click in Update():

if (onClick != null && onClick.GetInvocationList().Length > 0)
{
    OnClick(new EventArgs());
}

Then, when I create each button, it looks something like this:

MenuButton button = new MenuButton();
button.onClick += MethodToExecute;
menuButtons.Add(button);

MethodToExecute(object sender, EventArgs e) contains whatever actions I want the button to take.

Then I just simply loop through menuButtons to update and draw each as needed!

zuddsy
  • 2,455
  • 2
  • 13
  • 19