Godot Version
4.3
Question
I’m fairly new to using the await keyword. I’ve started using it in basic pieces of code to wait for an explosion to finish before doing a queue_free()
, for example. I started trying to get fancier, and now I’m running into a problem.
For now, while I’m still building everything, I’ve got some test code in the root Node2D _ready() function. This takes care of starting some music and randomly spawning some enemies. Worked fine until I refactored this:
# This works
$Music.playing = true
$BaddieSpawner.spawn_X_every_Y_seconds(asteroid, 10, 1)
await tree.create_timer(20).timeout
$Music.stream.set_sync_stream_volume(1,0)
$BaddieSpawner.spawn_X_every_Y_seconds(mine, 10, 1)
into this:
# This does not work
$Music.playing = true
$BaddieSpawner.spawn_X_every_Y_seconds(asteroid, 10, 1)
$LevelTimer.start(20)
await $LevelTimer.timeout
$Music.stream.set_sync_stream_volume(1,0) # <-- Errors out here
$BaddieSpawner.spawn_X_every_Y_seconds(mine, 10, 1)
(I made the change because timers I created on the tree would not pause when gameplay was paused.)
Problem is, after the await finishes in this new version, $Music seems to no longer exist. After waiting for 20 seconds, it throws this error: Invalid access to property or key 'stream' on a base object of type 'null instance'.
on the next to last line. Commenting that line out just makes it throw a similar error on the next line after being unable to suddenly find $BaddieSpawner. Looking at the Remote tab shows $Music as still being there, so I’m confused.
It feels kinda like when execution resumes it’s happening in a new thread or something; one that doesn’t have access to the original’s scope. But if that’s the case why did it work before?
I feel like there’s something fundamental I’m missing here. I know I could probably change this and get it working again by using lots of functions, but I’ll be needing much more timed events in my game and was planning on abusing awaits. More importantly, I just can’t figure out why this isn’t working and want to know.
I’m decently sure it’s because of the awaits, since commenting them out causes everything to start working again.
Thanks in advance for reading all this and possibly helping explain what I’m doing wrong.