onready var OR var in _ready? Putting reference to node in var or use $nodename?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Maz90

1: Should i put variables in onready var = … Or inside _ready function?
2: Should i reference a node in a vraiable or use $nodename instead?

:bust_in_silhouette: Reply From: Wakatta
  1. Honestly this is entirely up to you
    Like if you’re a one-liner junkie onready var is the way to go as it gives your code a sense of cleanliness and this becomes most apparent the more nodes you need to reference.

  2. Yes, yes and absolutely yes

Consider the following

onready var node = $nodename

func _ready():
    node.foo()

func _input(event):
    node.bar()

func _process(delta):
    node.foo_bar()

If you want another node to have the same functionality all you would have to do is change the reference

node = $another_nodename

Or if you decided to change name of the node there would only be one line to modify

onready var node = $different_node_name

There is also a matter of efficiency as there is a micro cost to calling the get_node func and even more so for the find_node one

Thanks man. appreciate it.

Maz90 | 2022-12-18 14:02