Is there any reason to use "var" instead of "onready var"?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Dadango
:warning: Old Version Published before Godot 3 was released.

Just wondering, so not urgent as to any project! (unless my understanding is completely off…)

Just dabbling around in Godot, having fun and learning stuff as we go, and almost all my variables (that are not local in functions or the like) are “onready” so they are ready when the scene loads.
Does this have any downside? When would you actual use “var” for a variable the entire script uses?

Have a nice day :slight_smile:

:bust_in_silhouette: Reply From: Zylann

A var is assigned a value when the script instance is created. At this point the node may not be ready on the scene (ex: you called instance() but not add_child) For that reason, you can set a default value to it that will be set only once, but it can’t be an expression related to the tree (like get_node or get_parent).

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(), also note that _ready() is also called when the node leaves and re-enter the tree again. Because of this initialization order, onready lets you assign values that depend on the tree you are instanced in, so you can use get_node with it.

The keyword is explained in the doc: GDScript reference — Godot Engine (latest) documentation in English

Note: using onready on scripts that are not extending Node (or derived) is kinda pointless^^"