Up to date

This page is up to date for Godot 4.1. If you still find outdated information, please open an issue.

Nodes and scene instances

This guide explains how to get nodes, create nodes, add them as a child, and instantiate scenes from code.

Getting nodes

You can get a reference to a node by calling the Node.get_node() method. For this to work, the child node must be present in the scene tree. Getting it in the parent node's _ready() function guarantees that.

If, for example, you have a scene tree like this, and you want to get a reference to the Sprite2D and Camera2D nodes to access them in your script.

../../_images/nodes_and_scene_instances_player_scene_example.webp

To do so, you can use the following code.

var sprite2d
var camera2d

func _ready():
    sprite2d = get_node("Sprite2D")
    camera2d = get_node("Camera2D")

Note that you get nodes using their name, not their type. Above, "Sprite2D" and "Camera2D" are the nodes' names in the scene.

../../_images/nodes_and_scene_instances_sprite_node.webp

If you rename the Sprite2D node as Skin in the Scene dock, you have to change the line that gets the node to get_node("Skin") in the script.

../../_images/nodes_and_scene_instances_sprite_node_renamed.webp

Node paths

When getting a reference to a node, you're not limited to getting a direct child. The get_node() function supports paths, a bit like when working with a file browser. Add a slash to separate nodes.

Take the following example scene, with the script attached to the UserInterface node.

../../_images/nodes_and_scene_instances_ui_scene_example.webp

To get the AnimationPlayer node, you would use the following code.

var animation_player

func _ready():
    animation_player = get_node("ShieldBar/AnimationPlayer")