Godot C# — Get the Reference of a Node and Attached Components
A beginner tutorial to get the reference of a Node in the scene.
It is a two-step process: get the NodePath
of the Node and then cast the NodePath
into the required type, which could be a Sprite
, Node
, RigidBody
etc.
Fetching the NodePath
This can be done by creating an editor-exposed variable (Unity Engine equivalent of SerializeField
) and dragging the Node
to the exposed property. It is also possible to search a Node
by its name.
Fetching the NodePath via a String Name
Simply use the GetNode
function. If this is all you’re after, you can skip the next section and move directly to the Type Conversion section.
var spriteNodePath = GetNode("MySprite");
However, we want to get the Node using an Editor Property.
Fetching NodePath via Editor Property
In this example, I have a CharacterCamera
class, and I am trying to get the reference of my player character Node (a KinematicBody
) so that I can move the camera based on the character’s position.
public class CharacterCamera : Camera
{
[Export] private NodePath _characterNodePath = null;
Build your solution. Then in the Editor, select the Node which carries the above script. Click the “Assign…” button on the exposed property, which is called “Character Node Path”.
This will bring up a “Select a Node” window. Click on the Node which you want to assign to the exposed property. In our case, it’s called “character”.
And now the Inspect should look like the following image.
Type Conversion
Now, we have the NodePath
of our character Node, but we want to get the type we need. In this case, our node is a KinematicBody
. The following code snippet shows how to accomplish that. There are other ways to make the conversion. Please refer to the documentation for more information.
private KinematicBody _characterKinematicBody = default;
public override void _Ready()
{
_characterKinematicBody = GetNodeOrNull<KinematicBody>(_characterNodePath);
}
And that's it; now we can use the _characterKinematicBody variable to get the character position.
Find Reference of an Attached Script
Continuing the example, next, we can get the reference of a CharacterController
script attached to the KinematicBody
. The as
operator will make the conversion or return null if it can’t find the specified script.
public override void _Ready()
{
_characterController = GetNodeOrNull<CharacterController>(_characterNodePath);
}