Address shared script used by multiple nodes

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

Hi everyone,

there is a tree structured like this:

-|- Control
–|- Sprite1
–|- Sprite2
–|- Sprite3

The Sprites share one Script containing a variable turn_something_on to be true or false…
From the Node2D’s Script I can address that variable in Sprite1 like this:
get_node("Control/Sprite1").turn_something_on = false (or true…)

This all works, but only for Sprite1. Is there a way to address that shared Script so the variable changes in all the Sprite-Nodes?

:bust_in_silhouette: Reply From: zhyrin

You can set turn_something_on on all sprites individually, if they are the only children of Control you could iterate over the children of Control and set it that way, you can put them into an array in Node2D and iterate over them in the array and set it that way.

Alternatively you can create a signal in Node2D, something like turn_on_requested(<new_value>), and you can subscribe to this signal with each sprite, in that case you only need to emit the signal once in your node2d. But I have to say, this is kind of the reverse of the convention of when you use signals. When you work with children, you usually call functions on them/set variables, when you work with siblings or parents, you emit signals.

Thanks for your answer!

Put things into an array… that pushed me into the direction of groups, so I just added all the Sprites to a group and then turned things on and off via get_tree().set_group. Thanks again for the hint!

pferft | 2023-06-27 16:55