What is the difference between get_node(@"MyNode") and $MyNode?

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

Hi everyone,

is there a difference between calling get_node with the “@” prefix or using the “$”?
Is there a difference in terms of performance?

The documentation (NodePath — Godot Engine (4.x) Dokumentation auf Deutsch) says, that a NodePath will be parsed ahead of time. So, I wonder, if this is the case with the “$” sign, too?

Regards

abgenullt

:bust_in_silhouette: Reply From: ejricketts

The general convention is to use “$” to assign a variable with the path to be used throughout your code, rather than having to call get_node() various times for the same thing. This leads to cleaner code that is much more readable.

Using “$” such as

onready var player = $Player

will run when the script has been checked through and will remain usable for the time the script is active in your game. However, by calling get_node(), this acquisition of the node will have to run each time the corresponding function it lies within is called, ie., more than once at the beginning of execution.

Both syntax can be used to store a node in a variable and both can be used to fetch a node every time it’s needed.

There’s no difference, $ is a syntactic sugar for get_node(@).

hilfazer | 2021-01-29 08:21

In practice, there isn’t a whole lot of difference for most projects (according to KidsCanCode).

$ is a lot better for readability

ejricketts | 2021-01-29 08:28

And what about this example from godot docs? It somewhat stays in opposition to what was said here and other places.

extends Node

Slow.

func dynamic_lookup_with_dynamic_nodepath():
    print(get_node("Child"))

Faster. GDScript only.

func dynamic_lookup_with_cached_nodepath():
    print($Child)

Fastest. Doesn’t break if node moves later.

Note that onready keyword is GDScript only.

Other languages must do…

var child

func _ready():

child = get_node(“Child”)

onready var child = $Child
func lookup_and_cache_for_future_access():
     print(child)

Does’n it mean that $ is faster than get_node() ???

VanDeiMin | 2022-01-15 21:53