Call a function with a variable for every member of a group

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

I understand how to call a function for every member of a group, like in the Docs:

get_tree().call_group(0, "guards", "player_was_discovered")

But is it posible that I can add a variable to the function, like by a normal function, for example:

func player_was_discoverd(variable):
:bust_in_silhouette: Reply From: njamster

Yes, just append the variables you want to pass in the end:

get_tree().call_group("guards", "player_was_discovered", 3, "Hohoho, got ya again!")

You can then use them like any normal arugment:

func player_was_discovered(times_catched, taunt):
    print("You have been discovered by guard number %d. He yells: %s" % [times_catched, taunt])

I tried it and it works with one or two variables, but if I have three or more variables it doesnt work any more. Is it necessary to change something, if I use three variables or can I only use one or two variables?

Godot_Starter | 2020-03-23 15:33

If you’re passing more arguments to the function like here:

get_tree().call_group("guards", "player_was_discovered", 1, 2, 3, 4)

you also have to adapt the function of course:

func player_was_discovered(arg1, arg2, arg3, arg4):
    print("%d %d %d %d" % [arg1, arg2, arg3, arg4])

You also can pass an array of arguments:

get_tree().call_group("guards", "player_was_discovered", [1, 2, 3, 4])

Then you can have a generic callback:

func player_was_discovered(args):
    print("%d %d %d %d" % args)

njamster | 2020-03-23 15:40

Thank you very much!

Godot_Starter | 2020-03-23 15:49