Question: What is the onready keyword in Godot?

Answer

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.

Example Usage

extends Sprite # Without 'onready', this would cause an error if accessed in '_ready()' because # 'get_node()' would be called before the node is ready in the scene tree. onready var sibling_node = get_node("../OtherNode") func _ready(): print(sibling_node.name) # Safe to access 'sibling_node' here

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.

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

Further Notes

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 _ready(), like _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.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Start building today

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