Godot Engine – How to create references to nodes
Last Updated on 7. January 2022 by Victor Karp
This tutorial explains how to create exported variables that reference nodes and how to combine this with static typing.
Why using $ or get_node() is problematic
To get a reference to a node in your node tree, you can use the $ sign followed by the node’s path. In a setup like on the next picture, you would put a script on the Player node and write $Camera to reference the camera. Alternatively, you can also write get_node(“Camera”).
Both notations cause problems when you move or rename the camera node, because the reference breaks and you have to fix the path. This is especially tedious for UI nodes that tend to be rearranged quite often.
Using an exported NodePath instead
Instead of relying on hard-coded paths, you can use an exported variable of the type NodePath instead like this:
export (NodePath) var my_camera
This creates a new field in the Inspector and allows you to pick the camera node by clicking on the Assign… button.
References that were created like this don’t break. You can move the node around inside the node tree or even rename it.
Using static typing for autocompletion
The disadvantage of exported NodePaths is that their type is unknown to Godot. This makes autocompletion impossible and forces you to know which functions and variables a node has. Until there is a native and more elegant solution for this, you can use the following workaround:
export (NodePath) onready var my_camera = get_node(my_camera) as Camera
This notation looks a bit strange, but causes Godot to resave the variable as a certain type when the node is ready. Due to the casting into a fixed type – in this case Camera – autocompletion works inside the script editor.
Credit for sharing this notation goes to the YouTube channel Tutemic and his fantastic video about Godot architecture.
Visit the Godot Tutorial main page for more Godot tutorials.