Alter variable in group via get_nodes or call_group

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

Hi everyone,

I put a var remote_counter = 0 into a button’s script (part of a group “the-other-buttons”) and then the

func _process(delta):
	if remote_counter == 15:
		_do_something()

A counter in a different button counts up on each button-press:

func _pressed():
	counter = (counter+1)

Is it possible to address the group and +1 their remote_counter directly from this func _pressed()?
Maybe with something like

func _pressed():
	counter = (counter+1)
	var the_other_buttons = get_tree().get_nodes_in_group("the-other-buttons")
	# or "get_tree().call_group"?
	the_other_buttons.counter = ( remote_counter + 1)

(This doesn’t work, obviously…)

:bust_in_silhouette: Reply From: zhyrin

You already found that you can get nodes in a group through the SceneTree.
It has even more functionality regarding goups, namely call_group(), notify_group() and set_group().
For your needs, the most convenient is call_group().

call_group calls a method within the members of the group, but my members don’t have such a common method, so what I want is a common variable to be altered directly… which actually works with set_group

get_tree().set_group("the-other-buttons", "remote_counter", (remote_counter+1))

That way tapping the group’s buttons randomly increases remote_counter in all of them simultaneously.

pferft | 2023-03-10 17:17

If you write remote_counter + 1 in set_group(), all the counters will update their value based on the one who called the set_group, not based on what is their current value.
The correct solution would be to have a setter function with the same signature on every node in the group, so they can increment their member value individually.

That is if you want all of them to have unique values. If not, it’s redundant to have the member variable in all of them.

zhyrin | 2023-03-11 20:43

Thanks for the hint. In my case, I actually want them all to “synchronize” whichever group-member is being tapped.

pferft | 2023-03-13 15:32