Topic was automatically imported from the old Question2Answer platform.
Asked By
Robster
Old Version
Published before Godot 3 was released.
Hi all,
I have 26 buttons (A…Z in the alphabet).
I want to connect them to a function so that when any button is pressed, the value of the text of the button is added to an array. In other words, I press the A button and the “A” of the text value is added to an array.
This question is about connections and functions though.
So I’ve started a test with my first three buttons by doing this:
The function _on_Button_released is as such for now for testing purposes:
func _on_Button_released():
print(self)
Currently the print outputs [Node572] no matter which of the three buttons I press.
What I’m trying to do is to to pass the button ID (or some such identifier) to the function _on_Button_released so that it can then process the text of that button.
Am I going about this the best way? I am new to it all and am a little stumped.
From /u/CowThing on reddit who helped me solve the same question:
for button in get_tree().get_nodes_in_group("my_buttons"):
button.connect("pressed", self, "_some_button_pressed", [button])
func _some_button_pressed(button):
print(button.name)
Ho MAN!
That’s amazing. I was about to go down an epic route of writing 26 small functions that fed into a single function to do the works. I can’t believe how efficient that is. The get_nodes_in_group function is incredibly powerful now I’ve done some reading on it.
I really want to thank you for that. My game is now working in its bare bone state. Now to finesse it!
Thanks again.
Robster | 2016-09-20 05:56
It worked for me , thanks.
fernan2cas96 | 2021-05-14 14:30
Is there a way to identify the buttons apart from by their name though, e.g. attach some data to them?
Edit: Toa nswer my own question, subclass the Button and add whatever you want.
So, assuming there’s a GridContainer we could add buttons to, the code could look like this:
func _ready():
for letter in "ABCD":
var button : Button = Button.new()
button.text = letter
button.pressed.connect(_button_pressed.bind(letter))
$GridContainer.add_child(button)
func _button_pressed(letter : String):
print("Button %s was pressed" % letter)