Need help with object instances - HELP

Godot Version

Godot 4.2.1

Question

Hello, I’m a new developer, and I’m new in Godot.
Here’s my issue :
I create multiple instances of button. No matter on which button I click, it’s supposed to hide some elements and show other. But my issue is that I need to get the info of which button as been clicked to adapt some settings. How can I do that ?

Here’s my code :

func _ready():
	if numberOfPlayers > 0:
			$CreatePlayerButton.hide()
			$CreatePlayerLabel.hide()
			for i in range(numberOfPlayers):
				var button = Button.new()
				$ScrollContainer/VBoxContainer.add_child(button)
				button.pressed.connect(self._button_pressed)
				button.custom_minimum_size = Vector2(0, 25)
		else:
			$CreatePlayerButton.show()
			$CreatePlayerLabel.show()
			$ScrollContainer.hide()
			$ScrollContainer/VBoxContainer.hide()
		
func _button_pressed():
	#elementsToHide
    #elementsToShow

Thanks for help !

When you supply self._button_pressed to connect it becomes a Callable. Callables can have additional arguments bound to them with the bind method, so you can bind the button to the callable when connecting the signal and then receive that bound argument in the connected method.

func _ready():
	...
        # Bind 'button' to the _button_pressed callable
		button.pressed.connect(self._button_pressed.bind(button))
	...
		
func _button_pressed(button):
    # button will be the button that was pressed

Additional documentation:

2 Likes