How to set multiple functions (func) in cycle?

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

I need to my cycles will create about 20 similar functions in code, can I even do this?

		button4ik.connect("pressed", self, "_on_"+str(button4ik.name)+"_pressed")

here “button4ik” it’s a button node which running in cycle, and this code create 20 signals for multiple nodes, but to create equal quantity of functions for it i can’t use something like:

func ("_on_"+str(button4ik.name)+"_pressed")

how can I solve that?

:bust_in_silhouette: Reply From: timothybrentwood

Hmm you’ll need to at the very least write the functions into your code. You can pass in things to your connect method so that will help identify which button was pressed, and which method to call. Here is an example of some of the things you can do:

func create_buttons(num_buttons):
    for index in range(num_buttons):
        var but = Button.new()
        but.connect("pressed", self, "_on_any_button_pressed", [but, index])
        self.add_child(but)

func _on_any_button_pressed(button_that_was_pressed, index_of_button_that_was_pressed):
    var functions_to_call = ["do_thing_one", "do_other_thing", "do_cool_thing"]
    if index_of_button_that_was_pressed == special_index:
        do_special_thing()
    elif button_that_was_pressed.text == "attack":
        attack()
    else:
        var the_function_name_to_call = functions_to_call[index_of_button_that_was_pressed]
        call(the_function_name_to_call)

thanks. you holier than people that build mosques

4to3aDebil | 2021-04-30 18:00