Creating a variable to point to a node vs calling the node directly

Hi,

I had a quick question about how the score updating section on the game over screen is handled. When I originally tried to do this myself before watching the video, I took the approach of using @onready and creating a variable to point to the $Panel/Score as seen below:

However, this results in an error when the player dies:

Whereas if I reference a node directly as in the video:

everything works as expected. What is the reason for this difference?

Thanks!

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

That makes a lot of sense! Thank you.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms