0 votes

Example:
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.

Thanks.

in Engine by (109 points)

1 Answer

+1 vote
Best answer

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).

by (10,229 points)
selected by

Hey,
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?

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

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

I would use a Singleton.

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.

Or just have the instances access the Singleton.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.