How to change properties of buttons generated via script

Godot Version

4.7

Question

I am creating a bunch of buttons via script, and connecting them to a function when pressed.What I cannot understand is how to change the pressed button’s properties within the function itself.

I would usually use .text, but I do not know what shoul I put before the dot.

You need a reference to those buttons.

If you’re generating said buttons in a loop, you can just access them right there when you connect their signal up.

button.text = "some text

If you need to change them later on, put the buttons in an array or a dictionary for easier lookup of specific buttons. It’s hard to tell and give accurate info with such little information.

You could also bind the button to the pressed handler, that way it’s accessible. Like this:

func _ready() -> void:
    for i in range(5):
        var b := Button.new()
        b.text = "Button %d" % i
        add_child(b)
        b.pressed.connect(_on_pressed.bind(b))

func _on_pressed(pressed_button: Button) -> void:
    pressed_button.text += "!"

This code adds an exclamation mark to the button when it’s pressed. You “bake in” the button argument into the pressed handler with the bind() method. I use it all the time like this :slight_smile:

You could also do this and it would work the same way. Although I suspect the first version may be more performant.

b.pressed.connect(func() -> void: _on_pressed(b))

Thank you! That’s what I was missing, the bind() method. Now it all works fine :slight_smile: