0 votes

Hello,
I have an issue creating new signals in script. This is my case:
I have a vbox that is populated from an array with texture buttons. I need those buttons to do different things when they are pressed.
If I connect each child to a pressed signal how would I go about creating the target functions when I don't know how many do I need, or maybe I can make only one function and send a parameter with the signal ?

Thank you

in Engine by (17 points)

1 Answer

+1 vote
Best answer

I recomend you to look at the command design pattern ( https://www.geeksforgeeks.org/command-pattern/).
In my opinion it's the easiest way to implement multiples buttons doing differents things. The advantage is :
- you don't have to create a class by button
- your button are independant ( you don't bother with a parent or other object, your button can work alone)
- the signal is treated in the button

here's some code for the button:

extends Button

class_name ButtonCommand

var _command = null

func set_command( command : Command)-> void:
    _command = command

# Don't forget to connect the button in the editor or do it in the ready function

func _on_Control_pressed() -> void:
    _command.execute()

I think the article is well detailed and easy to understand to be adapted to your project.

by (288 points)
selected by

Thank you for your answer, I didn't knew about this.
Because my commands are few(4) in number I managed to get it working by setting parameters for each button and treat each case.

for x in vbox.get_children():
    x.connect("pressed", self, "interceptLinks", [globals.notificationArray[temp].type, globals.notificationArray[temp].village])


func interceptLinks(type, village) << treated the 4 cases here

Treating cases like this works in this particular situation but your solution is better when you have to usually deal with more multiple button actions so you don't have to write tens of statements, thank you for the information.

Glad to help you. You can select the answer so other will see this question is solved :)

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 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 webmaster@godotengine.org with your username.