Question: When should you use the "onready" keyword in Godot?


The 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 onready:

  1. 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.

  2. Safer than _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:

extends Sprite # Without 'onready', this would cause an error if accessed too early. onready var child_node = get_node("ChildNode") func _ready(): # Safe to use 'child_node' here - it's guaranteed to be initialized. child_node.do_something()

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.

Using 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.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.