onready keyword in Godot is used when you want to initialize a variable with an instance from the node tree, but you need to ensure that the node tree is fully ready and instantiated before doing so. The
onready keyword delays the initialization of the variable until the node (where the script is attached) and all its children are inside the scene tree and ready.
Here's why and when you would typically use
Initialization Timing: You can't safely access child nodes in the constructor (
_init()) because they may not be part of the scene tree yet. Using
onready ensures that the nodes exist.
_ready(): While you could initialize such variables in the
_ready() function, using
onready lets you declare them with other class member variables at the top of your script for better organization and readability.
Below is an example where
onready is useful:
In this example,
child_node will only be assigned once the
_ready() callback is activated for the
Sprite, ensuring that
"ChildNode" is part of the active scene and thus can be safely accessed.
onready is particularly useful when working with complex scenes where the initialization order matters or when dependencies between nodes are crucial to the game's functioning.
However, you should avoid overusing
onready for everything, as it might hide certain dependency structures in your code which could lead to harder maintainability. Use it judiciously for cases where you specifically need to wait for the scene tree's readiness state.