Signals and target functions

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By outofblue

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

:bust_in_silhouette: Reply From: UnRealCloud 1

I recomend you to look at the command design pattern ( Command Pattern - GeeksforGeeks).
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.

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.

outofblue | 2020-07-29 09:21

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

UnRealCloud 1 | 2020-07-29 10:09