How to "properly" reference Nodes?

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


I was curious about the proper way to reference Nodes in the Godot Engine. By reference, I mean doing things such as calling a Node’s method or accessing a Node’s variable.

I know that $ and get_node work the same, but I was wondering whether or not it is faster to save a reference to the node in a variable, such as using by using onready.

Is it cleaner to just get the Node mid-script, or to keep it as a variable?

Thank you!

:bust_in_silhouette: Reply From: Gluon

There is no simple answer to this as it depends on your game its complexity and how many times you need to call the reference. In principle from the point of view of the game it really wont matter, there is next to no difference in processing power etc but I would personally recommend creating a variable and storing the reference to the node. It makes writing and debugging your code a lot easier. If you have written it once correctly you wont get errors from silly spelling mistakes on a get node latter in the code. Just my suggestion though there isnt a right or wrong way to do it.

I should probably mention I mis-spelled later incorrectly on purpose, it was supposed to be funny but actually might be lost in a written format.

Gluon | 2022-11-20 18:14

Thank you! One more thing, would you recommend creating a reference variable if the Node is only referenced once, or should I just reference it directly?

SQBX | 2022-11-20 18:36

If you are sure it will only be referenced once then thats fine but to be honest I would probably still create a variable. As games get more complex you can find that you only intended to reference it once but find something you want to add later may need it again. Its also generally good to get into the practice of doing something if you intend it to be your standard coding technique. As I say though there is no right or wrong here.

Gluon | 2022-11-20 18:46