How does Godot know in which order to call _ready functions if nodes depend on one another?

My question is how does Godot know in which order to run the _ready functions and can I rely on everything just being there when I need it? I mean, it’s awesome that it works, but I don’t understand how :thinking:

Here’s how the question came up:
I got an error which was not related to my code, but to a script not being attached to a node (don’t ask me how I managed to do that :woozy_face:), so I got this error:

Invalid call. Nonexistent function ‘update_GUI’ in base ‘Nil’.

This made immediate sense to me, because I was calling the function of a node whose _ready has to be run to be registered globally so it can be called in another node’s _ready function. I can’t tell Godot in which order the nodes should run their _ready functions, so that’s the reason for the error, I thought.
But that’s not the case!

Here’s some code snippets to make the whole thing a little clearer, hopefully:

# Global
var GUI
# GUI
func _ready():
	Global.GUI = self
# GameState 
func _ready():
	Global.GameState = self
	lives = starting_lives
	update_GUI()

func update_GUI():
	Global.GUI.update_GUI(lives)

Thanks to Zylann in Godot Engine QA I found this:

An onready var is assigned a value after the node and its siblings entered the tree. It’s a shortcut for assigning variables in _ready(). onready lets you assign values that depend on the tree you are instanced in.

for example:

extends something

onready Global.Gamestate = self

func _ready():
    lives = starting lives
    update_GUI()

I’m not sure if this works but it is very helpful on those get_node() or $ things

https://godotengine.org/qa/12000/is-there-any-reason-to-use-var-instead-of-onready-var

Thank you @p4nu!
That does make sense and I guess it’s clear enough, although I still don’t know how the order of the different _ready function calls is determined, but I guess I can live with that for now :slight_smile:

It obviously works, because the _ready function and the onready declaration are meant for the exact case I’m interested in: Accessing one node from another node.

I forgot to tell you that the ready functions gets called in the order they are in the Scene Tree. So the main node calls the _ready() first and then what’s under it.

kuva
In this case the node “Platforms” calls the _ready() first and then Sprite calls it’s own _ready() and so on.

1 Like

Oh, that’s simple enough, awesome!
Thanks again!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms