Godot Version
4.4dev7
Question
My code needs to access @onready
variables of a freshly-created node. When trying to conditionally wait for the .ready
signal like this:
if !player.is_node_ready():
await player.ready
# the code that needs `@onready var`s of `player`
I reliably get a TOC/TOU bug. How do i solve this?
Await does not block, it creates a subroutine, of the remaining function block, that will finish when the signal happens. It also immediately returns from the function block to the caller, allowing the mainloop to continue running.
Usually if you create a node they can be readied by using add_child(new_node) on a node thats already part of the scenetree, after this point all nodes will be ready. (If it isnt, You may need to wait a process cycle, i remember needing to do funny things for unit tests but i cant recall fully atm.)
You need to share more code.
Also @onready should be used on child nodes only. Siblings can work, but only if they are lower in the scene tree, as readiness goes bottom up. Sibling and parent use is not recommended. Use @export instead.
Lastly ready only happens once. If a scene is added to the SceneTree, removed, and added again, ready will not be signaled again.
2 Likes
Usually if you create a node they can be readied by using add_child(new_node) on a node thats already part of the scenetree, after this point all nodes will be ready.
This was the missing puzzle piece, thank you! This isn’t mentioned in the docs of Node.add_child
, so i assumed that pre-ready processing/“ready countdown” begins right when the script/scene is created/instantiated. Simply changing the code from:
# processing code that relies on @onready variables of `player`, with checks for ready-ness
add_child(player)
to
add_child(player)
# processing code that relies on @onready variables of `player`, ready-ness checks not needed
solved the issue!
As for the rest, i still appreciate the effort in explaining!
Yep, it was (expectedly, if i’m being honest) my fault all along: Node
’s docs explain this exact condition for a node to become ready:
Once all nodes have been added in the scene tree, they receive the NOTIFICATION_READY notification and their respective _ready callbacks are triggered. For groups of nodes, the _ready callback is called in reverse order, starting with the children and moving up to the parent nodes.
1 Like