Connecting Multiple Buttons in Same Script c#


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!

either override _Pressed() or += your method to Pressed. below shows both ways.

using Godot;
using System;

public partial class MyButton:Button {
	void Function1() {
	void Function2() {

	// override _Pressed()
	public override void _Pressed() {
		GD.Print($"Button clicked has name: {Name}");

	// use Pressed += method
	public override void _Ready() {
		if("Button1" == Name) {
			Pressed += Function1;
		else if("Button2" == Name) {
			Pressed += Function2;

1 Like

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()