Connecting Multiple Buttons in Same Script c#

Hello,

I have a scene with multiple buttons as children in a UI. I want to connect multiple buttons to my main UI script. I have the first button connected using OnButtonPressed(). It seems like in GDscript you can use _on_button2_pressed, but cant use OnButton2Pressed in c#. Is there any way to add a new OnButtonPressed function for a different button? Please help. Thank you!

Thanks for the Reply! Im a beginner at coding so I didn’t quite understand.
Here is my current code. Im not sure why it isn’t working. when I press button.

private void OnButtonPressed(object sender, EventArgs e)
{
Button senderButton = (Button)sender;
if (senderButton == GetNode<Button (“Button”))
{
}

It’s hard to tell without seeing your code, but if what you’re trying to do is connect all button click events to a single handler, what I’d do is get all button elements, and iterate through each one, connecting the Pressed event to your function.
I have an example of this in my project as well, here:

_buttonContainer = GetNode<GridContainer>("VBoxContainer/DialButtons");
foreach (var node in _buttonContainer.GetChildren())
{
	var button = (ActionButton)node;
	button.ActionPressed += ButtonOnActionPressed;
}

The only difference in my case is that I have a custom event tied to these buttons called ActionPressed, but you can use the normal Pressed event as well, and it’ll work.

1 Like

Thank you guys! All I had to do was connect the button in the editor to OnButton2Pressed. Very simple haha.

private void OnButton2Pressed()

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.