Chuyển đến nội dung

Bài 6 · Editor and Scenes

Godot Scenes and the Scene Tree Explained

Understand Godot's core design: nodes, scenes, the SceneTree, parent-child relationships, node paths, ready order and how Godot walks the tree each frame, with a runnable model.

Everything in a running Godot game lives in one big tree called the scene tree. Understanding it makes almost every other topic easier: why a child moves with its parent, why _ready runs in a particular order, how to find a node by path, and why deleting a node deletes everything below it. This lesson explains scenes, nodes and the tree, and lets you run a faithful Python model of the traversal rules.

The real SceneTree runs only inside Godot. The Python snippets here are stand-ins that reproduce the rules, not the engine. Godot snippets are read-only.

Nodes, scenes and the tree

A node is the smallest unit: it has a name, a type, properties, an optional script and children. A scene is a saved node tree (.tscn). When your game runs, Godot loads the main scene and attaches its root to the SceneTree, which owns a built-in root called the Window (/root). Your main scene's root becomes a child of it.

flowchart TD
    Root["/root (Window)"] --> Main["Main"]
    Root --> Auto["GameState (autoload)"]
    Main --> World["World"]
    Main --> HUD["HUD"]
    World --> Player["Player"]
    World --> Enemy["Enemy"]
    Player --> Sprite["Sprite2D"]

Autoloads (see Autoloads, Timers and Tweens) also sit under /root.

Rules of the tree:

  1. A node has one parent (except the root) and any number of children.
  2. Sibling names must be unique under the same parent. Godot renames duplicates (Enemy, Enemy2) or @Enemy@2 for runtime-created nodes unless you set a name.
  3. A node's position in the tree gives it a path: /root/Main/World/Player.
  4. Deleting a node deletes its whole subtree.
  5. Children inherit some things from parents: transform, visibility, and (for physics) the pause state.

Finding nodes by path

Relative paths start from the node running the script.

GDSCRIPT
extends Node

func _ready() -> void:
    var hud := get_node("HUD")                   # child named HUD
    var sprite := get_node("World/Player/Sprite2D")
    var same := $World/Player/Sprite2D           # shorthand for the line above
    var parent := get_parent()
    var root := get_tree().root                  # the Window
    print(sprite.get_path())                     # /root/Main/World/Player/Sprite2D
  • $Name is get_node("Name"). Use quotes when names contain spaces: $"My Sprite".
  • %Name finds a unique-name node: right-click a node in the Scene dock and choose Access as Unique Name, then %Health works from anywhere in that scene regardless of depth. It survives reorganizing the tree.
  • .. means the parent: get_node("../Camera2D").

If a path is wrong, get_node prints an error and returns null; get_node_or_null returns null quietly, which is handy for optional nodes.

The order things happen

Godot visits the tree in depth-first order. The two rules to remember:

  • _ready is called after the children's _ready: children first, parent last ("bottom-up"). That is why a parent can safely use its children in _ready.
  • _process and _physics_process are called top-down: parent before children, in tree order (top of the Scene dock to the bottom).

Also, when you call add_child(node), the new node's _enter_tree and then _ready run immediately if the parent is already in the tree.

GDSCRIPT
# player.gd
func _enter_tree() -> void: print("enter: ", name)   # top-down
func _ready() -> void: print("ready: ", name)        # bottom-up

For the tree above, the output is enter for Main, World, Player, Sprite2D (parents first), then ready for Sprite2D, Player, Enemy, World, HUD, Main (children first).

Stand-in: walking a tree in Godot's order

Run this Python model and compare with the rules above.

Python Stand-in (Python): enter_tree, ready and process order

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You should see the ready lines list Sprite2D before Player and Main last. The last two lines print /Main/World/Player/Sprite2D and /Main/World/Enemy.

Working with the tree from code

GDSCRIPT
var bullet := Node2D.new()
bullet.name = "Bullet"
add_child(bullet)             # now part of the tree
remove_child(bullet)          # detached, but still in memory
bullet.queue_free()           # delete safely at the end of the frame
  • queue_free() is the normal way to delete a node: it waits until the frame ends, so other code does not use a node that vanished mid-function. Calling free() immediately can crash if something still refers to the node.
  • get_children() returns an array; get_child(0) the first.
  • is_inside_tree() tells you whether a node is currently in the running tree. Nodes created with .new() are not until you add_child them.
  • get_tree().change_scene_to_file("res://level2.tscn") swaps the main scene.
  • get_tree().paused = true pauses nodes unless their process_mode says otherwise.

Common mistakes

  • Using $Child in a variable initializer without @onready: the child does not exist yet.
  • Forgetting add_child: a node created in code is invisible and its _ready never runs until it is in the tree.
  • Calling free() on a node during its own signal handler. Use queue_free().
  • Hard-coding long paths ($"../../Player"). Prefer exports, groups or unique names, see Node Communication and Groups.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. In what order is _ready called for a parent with children?

    _ready is bottom-up so a parent can safely use its children. _process is top-down.
  2. 2. What does the path /root/Main/World/Player describe?

    Node paths describe positions in the scene tree, starting at /root.
  3. 3. What is the safest way to delete a node during a frame?

    queue_free() defers deletion to the end of the frame, avoiding use-after-free problems.
  4. 4. What does %Health do in GDScript?

    % accesses nodes marked 'Access as Unique Name' inside the same scene, independent of their depth.
  5. 5. What happens to children when you delete their parent?

    Deleting a node removes its entire subtree.

Summary

  • A game is one SceneTree under /root; scenes are saved subtrees of nodes.
  • Nodes have a single parent, unique sibling names, and a path.
  • $Name, %Unique and get_node() find nodes; get_node_or_null is the quiet variant.
  • _ready runs children first; _process runs parents first.
  • Delete with queue_free(), and remember add_child before a new node does anything.

Next: Nodes and 2D Transforms

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.