|Topic was automatically imported from the old Question2Answer platform.
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
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
Is it cleaner to just get the Node mid-script, or to keep it as a variable?
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.
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?
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.