I want to connect the pressed signal of 9 buttons by code but since the .connect method doesn’t use a string argument (which I could easily modify in my loop) I don’t know how to connect each of them.
I want to do something like this:
for i in buttonArray:
get_node("button%d" %i).pressed.connect("on_pressed_button_%d" %i)
Expecting it will connect the 9 pressed signals to my 9 on_pressed_button function
I found a post for an older Godot version that use only one "on_pressed" function for the whole list and get the button in the parameter.
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)
Is something like this still possible in the actual 4.1 version ?
I was able to solve this by using Callables and the call(String)
function.
extends Node2D
func _ready():
for button in $ButtonList.get_children():
button.pressed.connect(func(): call("on_pressed_"+button.name) )
func on_pressed_Button1():
print("1")
func on_pressed_Button2():
print("2")
func on_pressed_Button3():
print("3")
func on_pressed_Button4():
print("4")
func on_pressed_Button5():
print("5")
Doing this works but requires you to have a function for each button and is name sensitive (you could work around this using the index like you started doing).
The other way of doing it like you said is connecting all the buttons to a single function and passing the button as an argument. You can do this with the bind
function.
extends Node2D
func _ready():
for button in $ButtonList.get_children():
button.pressed.connect(on_pressed.bind(button))
func on_pressed(button):
print(button.name)
This adds the button as an argument to the Callable.