Nice find! On first glance, there is no reason this shouldn’t work (but it definitely has something to do with exactly when _ready()
is being called in relation to everything else happening to the gameover scene), so I downloaded the course project to have a closer look.
It turns out this is exactly the sort of bug that makes me consider it a best practice to place your add_child()
line immediately after your instantiate()
line. It isn’t always the best approach because there are situations in which you might get a flicker on initialization, but it prevents errors like this, so it’s probably better to do it this way until you have a reason not to.
In the game script, the course code sets the gameover score before adding the scene as a child. This doesn’t work with an @onready
reference because _ready()
is called when the scene is added as a child, so the reference isn’t built yet at the time the gameover set_score()
is attempting to use it. Adding the child first and then setting the score is enough to make everything work.
The reason it works by default when using the direct reference like in the video is because that builds the reference immediately, not during _ready()
, so the reference is complete right after instantiate()
. Hope that clears everything up =)