0 votes

How can I get value from a pressed button that was created in a loop.

I created 3 buttons:

func genButtons():
    for i in 3:
        buttons.append(Button.new())
        buttons[i].text = str(modText[MOD][i])
        add_child(buttons[i])

But I am not sure how to figure out which button I pressed?

Godot version 3.5.1
in Engine by (42 points)

1 Answer

+1 vote

You'll want to wire a pressed event to each button, and then pass the button reference through the callback. From there, you can directly access the pressed button's data, including it's text property (assuming that's what you mean by value). Untested (and adding to your code above), but something like:

func genButtons():
    for i in 3:
        var button = Button.new()
        buttons.append(button)
        button.text = str(modText[MOD][i])
        add_child(button)
        button.connect("pressed", self, "_button_pressed", [button])

func _button_pressed(button):
    print(button.text)
by (19,302 points)

So other may benefit from my question. This one worked for me

func genButtons():
    for i in 3:
        buttons.append(Button.new())
        buttons[i].text = str(modText[MOD][i])
        add_child(buttons[i])
        buttons[i].connect("pressed", self, "_button_pressed", [buttons[i]])

func _button_pressed(button):
    print(button.text)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.