Make a function wait until a timer in another function is finished

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

I am developing a Shoot 'em up with a spawn script for enemy waves. I spawn the enemies in a function “wave 1” called in _ready(). In this Wave-Spawn Function I create enemies with this line:spawn_enemy_group(type, amount, *time_between_enemies*, *time_after_spawning_all_enemies*)

In the spawn_enemy_group-function I am using:
await get_tree().create_timer(time_between_enemies).timeout
after each enemy and
await get_tree().create_timer(time_after_spawning_all_enemies).timeout
after spawning all enemies

My problem is that the wave script will go on altough the timer in the spawn-function isn’ t over yet. How can I make the wave-function wait until the timer in the spawn_enemy-function is over?

This seems like the ideal use case for a signal, which you then yield on from the other function. For example, a finished_spawn_enemy signal.

spaceyjase | 2023-03-24 16:54

:bust_in_silhouette: Reply From: codabase

Here’s a quick guide on signals that might be helpful for you!

:bust_in_silhouette: Reply From: zhyrin

Since you access the return value of get_tree().create_timer() on those lines only, they are local variables you can’t access outside of the scope of your function.

You could a) write the created SceneTreeTimers into variables and await on them in different functions as well or b) use Timer nodes instead which might be a bit easier to reference in multiple places.