IndustryStandard Could someone explain it to me like I'm 5 on why I would use onready over var? Maybe with a nice little metaphor.
@onready var foo = 42
is basically just syntactic sugar for:
var foo
func _ready():
foo = 42
It's just shorter and more readable.
Now why would you want to do something like this? Simply because you cannot always assign something while the script is loading and you have to wait until it's ready.
You can assign simple, constant values at script load time like var foo = 42
without a problem. But you cannot write something like this: var camera_3d = $Camera3D
(note the missing @onready
) At script load time the node "Camera3D" doesn't exist yet! Therefore you have to wait until it exists, which is when your script is ready. Because at that point in time all its children have been initialized and are ready as well.
So to solve this problem you would write something like this:
var camera_3d
func _ready():
camera_3d = $Camera3D
Or in short: @onready var camera_3d = $Camera3D
To give an analogy think of it like this:
- You want to play a game that isn't installed yet.
- You open Steam and your see the name of the game in your library. This is the equivalent to script load time where you "see" the name of the variable itself but there is no value behind it. Just like there is no game (or game files) behind the name in your games list because it's not installed yet.
- You install the game. Once it's downloaded it is ready.
- And now Steam is ready to play your game because now there is an installed game behind that name in your games library.