Question: When is the `ready` function called in Godot?

Answer

In Godot Engine, the _ready() function is a callback that is called once when a node and all its children have entered the scene tree. This happens after the engine initializes the node and ensures it is part of the active scene. Essentially, this is the first opportunity to perform setup tasks on a node that requires knowing that all of its children are present and initialized.

Here's how you would typically override the _ready() function in GDScript:

extends Node func _ready(): # Initialization code here

The _ready() function is an excellent place to find nodes, initialize variables, or connect signals because at this point you can be certain that:

  • All child nodes have been instantiated.
  • The current node has been added to the scene.
  • Nodes are ready to communicate with each other.

It's important to note that _ready() is only called once for any given node, just before the first frame where the node is present. If a node is removed from the scene and re-added, the _ready() function will be called again upon re-entry into the scene.

Also, if you're creating nodes dynamically during runtime (i.e., via instance()) and adding them to the scene with add_child(), you may want to call their _ready() manually if necessary, though usually, Godot calls _ready() automatically on the next frame after the node is added to the scene.

Here is an example of dynamic instantiation:

var my_node = preload("res://my_node.tscn").instance() add_child(my_node) # No need to call my_node._ready() as Godot will call it automatically.

Keep in mind that the _ready() method should not perform heavy computations or operations that could cause a delay in the rendering of the first frame. If complex or time-consuming initialization is required, consider spreading it out over multiple frames or using background threading if appropriate.

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.