Change variable in every instance

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

I have 15 instances of ball.
These all fall down one after the other. However, when I press a button, they should all fall down with more speed (As with Tetris).

Something like that would normally be done with a static variable. Which then changes the speed of everyone. But I can’t find a solution to give every ball the same value.


:bust_in_silhouette: Reply From: njamster

If you define the speed variable in the instance, then yes, that variable is specific to precisely that one instance. So you would need to loop over all 15 instances of your ball and change the variable for each one of them:

for i in range(15):
    get_node("Ball" + str(i)).speed = 400

Alternatively you can store that same variable in a global script (a so-called Singleton) and setup your ball script in a way, that it get’s the speed from there:

move_and_collide(direction * Global.Speed * delta)

Then you only have to change the value once (in the global script).

thanks for the quick reply.
So it is not a variable that I create myself but I just wanted to access “gravity scale”.
So can’t just I change this value from all instances with a small command?

Krippi | 2020-03-03 13:50

Doesn’t matter. That’s still a per-instance-variable - even if you didn’t define it yourself. Loop over all ball instances and change thegravity_scale individually. You can add them to a group for easier access and then loop over it by using:

for ball in get_tree().get_nodes_in_group("balls"):
    ball.gravity_scale = 0.5

njamster | 2020-03-03 14:26

okey that works i guess. ^^ Thanks
I ask again when i got a question about this topic.

Krippi | 2020-03-03 14:44

I would use a Singleton.

Merlin1846 | 2020-03-03 15:44

I would use a Singleton.

You would still need to access every instance and tell it to fetch the updated value from the Singleton (or have every instance poll the Singleton for it each frame).

I think looping over all instances is easier.

njamster | 2020-03-03 16:13

Or just have the instances access the Singleton.

Merlin1846 | 2020-03-04 15:38