In Godot, the
onready keyword is used as a modifier for variable declarations. When you use
onready before a variable, it means that the assignment of that variable will be delayed until the instance of the node to which the script is attached has entered the scene tree. This is particularly useful when you want to initialize variables with references to other nodes in the scene.
Here's why this is important: if you try to get a reference to a node in your scene during the regular
_ready() function without
onready, and that node hasn't been initialized yet, you'll get a null reference resulting in an error. The
onready keyword ensures that all the nodes have been instantiated properly before you try to access them.
In this example,
sibling_node is only assigned after the node has been added to the scene, which is when
_ready() is called. Thus you can safely assume that
sibling_node points to a valid object once
_ready() begins executing.
onready is a good practice when setting up scripts that depend on the scene tree hierarchy, ensuring that your references are valid and avoiding common errors that occur due to uninitialized nodes.
onready is not just for nodes; it can be used with any resource or object reference that needs to be initialized at the right time in the lifecycle of a script. However, it's most commonly used with nodes for the reasons outlined above.
Keep in mind that
onready variables are not initialized until the node enters the scene tree. Therefore, they cannot be accessed in functions that may execute before
_init(). If you need to access nodes in
_init(), you must rely on different strategies, such as manually initializing them later in the code, after you're certain that the entire scene tree is ready.