Godot Nodes & Scenes (4.x)
Compose games from nodes and scenes, instance them at runtime, and access the tree
without crashing on freed or missing nodes. Targets Godot 4.7.
When to use
- Use when structuring
.tscn scenes, choosing how to break a feature into nodes,
instancing a PackedScene (bullets, enemies, UI), or setting up autoload singletons.
- Use when debugging
get_node() / $Path returning null, or "Attempt to call on a
previously freed instance".
When not to use: GDScript language/syntax → godot-gdscript; signal-based
decoupling → godot-signals-groups; physics bodies/collisions → godot-physics.
Core workflow
- Model with composition. A scene is a tree of nodes saved as
.tscn. Build small,
single-purpose scenes (Player, Bullet, Enemy) and compose larger scenes from them.
Favor adding child nodes over deep inheritance.
- Make a scene reusable by giving its root a script and exposing
@export config.
Save it; it becomes a PackedScene you can instance many times.
- Instance at runtime with
preload/load → scene.instantiate() →
add_child(instance). Set position/state after adding (or before, both work).
- Access nodes safely. Use
@onready var x = $Path for fixed children; use unique
names (%Name) for nodes deep in the tree; never assume a node still exists.
- Use autoloads for global state/services (game state, audio, scene switching) —
registered in Project Settings > Globals (Autoload), accessible by name everywhere.
- Free nodes with
queue_free() and guard later access with is_instance_valid().
Patterns
1. Instance a scene at runtime
extends Node2D
const BULLET := preload("res://bullet.tscn") # preload: loaded at compile time
func shoot(at: Vector2, dir: Vector2) -> void:
var bullet := BULLET.instantiate() # create an instance of the scene
bullet.global_position = at
bullet.direction = dir # set exported/public state
add_child(bullet) # now it's in the tree and runs
2. Safe node access: $, get_node_or_null, and unique names
@onready var label: Label = $UI/Label # $ is sugar for get_node("UI/Label")
@onready var health_bar: ProgressBar = %HealthBar # % = scene-unique name (rename-proof)
func update() -> void:
var optional := get_node_or_null("Maybe/Missing") # returns null instead of erroring
if optional:
optional.queue_free()
3. An autoload singleton (global game state)
# game_state.gd — add in Project Settings > Globals > Autoload as "GameState".
extends Node
var score := 0
signal score_changed(value: int)
func add_score(points: int) -> void:
score += points
score_changed.emit(score) # any scene can: GameState.score_changed.connect(...)
4. Change the running scene
func go_to_level_2() -> void:
# Swaps the current scene for another. Frees the old scene tree.
get_tree().change_scene_to_file("res://levels/level_2.tscn")
# Or, with a preloaded PackedScene:
# get_tree().change_scene_to_packed(LEVEL_2)
Pitfalls
$Path / get_node() return null or error when the path is wrong or the node
isn't in the tree yet. Use @onready, verify the path matches the scene, or use
get_node_or_null() for optional nodes.
- Renaming a node breaks
$Path. Use unique names (%Name, set via right-click
Access as Unique Name) so deep references survive renames and reparenting.
free() mid-frame can crash other code still using the node. Prefer
queue_free() (deletes at end of frame) and check is_instance_valid(node).
- Setting child state before
add_child() is fine, but _ready() on the child only
runs after it enters the tree — don't expect its @onready vars before that.
- Autoload order matters: autoloads are added before the main scene, in list order.
An autoload can't depend on the main scene existing yet.
instance() was renamed to instantiate() in Godot 4. preload runs at parse
time (path must be constant); load runs at runtime (path can be a variable).
change_scene_to_file() is deferred, not immediate — Godot swaps and frees the old
scene at the end of the current frame. Any code after the call still runs against the old
tree, and get_tree().current_scene isn't the new scene until next frame. Don't read the new
scene's nodes on the same line; do it from the new scene's _ready().
References
- For scene inheritance,
owner/ownership when saving scenes from code, groups vs
unique names, and node-path edge cases, read references/tree-and-instancing.md.
Related skills
godot-gdscript — language, lifecycle, and @onready.
godot-signals-groups — decouple instanced scenes from their spawner.
godot-resources — share data between instances without duplicating it.
save-systems — persist scene/game state across runs.
1---2name: godot-nodes-scenes3description: Structure a Godot 4.7 project with the scene tree and node composition: build reusable scenes, instance PackedScenes at runtime, navigate the tree safely, and register autoload singletons. Use when designing .tscn scenes, deciding how to split nodes, spawning instances with instantiate(), wiring autoloads, or fixing "node not found"/freed-node errors in a Godot project.4---5
6# Godot Nodes & Scenes (4.x)
7
8Compose games from nodes and scenes, instance them at runtime, and access the tree
9without crashing on freed or missing nodes. Targets **Godot 4.7**.
10
11## When to use
12
13- Use when structuring `.tscn` scenes, choosing how to break a feature into nodes,
14 instancing a `PackedScene` (bullets, enemies, UI), or setting up autoload singletons.
15- Use when debugging `get_node()` / `$Path` returning `null`, or "Attempt to call on a
16 previously freed instance".
17
18**When _not_ to use:** GDScript language/syntax → `godot-gdscript`; signal-based
19decoupling → `godot-signals-groups`; physics bodies/collisions → `godot-physics`.
20
21## Core workflow
22
231. **Model with composition.** A scene is a tree of nodes saved as `.tscn`. Build small,
24 single-purpose scenes (Player, Bullet, Enemy) and compose larger scenes from them.
25 Favor adding child nodes over deep inheritance.
262. **Make a scene reusable** by giving its root a script and exposing `@export` config.
27 Save it; it becomes a `PackedScene` you can instance many times.
283. **Instance at runtime** with `preload`/`load` → `scene.instantiate()` →
29 `add_child(instance)`. Set position/state _after_ adding (or before, both work).
304. **Access nodes safely.** Use `@onready var x = $Path` for fixed children; use unique
31 names (`%Name`) for nodes deep in the tree; never assume a node still exists.
325. **Use autoloads for global state/services** (game state, audio, scene switching) —
33 registered in Project Settings > Globals (Autoload), accessible by name everywhere.
346. **Free nodes with `queue_free()`** and guard later access with `is_instance_valid()`.
35
36## Patterns
37
38### 1. Instance a scene at runtime
39
40```gdscript
41extends Node2D
42
43const BULLET := preload("res://bullet.tscn") # preload: loaded at compile time
44
45func shoot(at: Vector2, dir: Vector2) -> void:
46 var bullet := BULLET.instantiate() # create an instance of the scene
47 bullet.global_position = at
48 bullet.direction = dir # set exported/public state
49 add_child(bullet) # now it's in the tree and runs
50```
51
52### 2. Safe node access: $, get_node_or_null, and unique names
53
54```gdscript
55@onready var label: Label = $UI/Label # $ is sugar for get_node("UI/Label")
56@onready var health_bar: ProgressBar = %HealthBar # % = scene-unique name (rename-proof)
57
58func update() -> void:
59 var optional := get_node_or_null("Maybe/Missing") # returns null instead of erroring
60 if optional:
61 optional.queue_free()
62```
63
64### 3. An autoload singleton (global game state)
65
66```gdscript
67# game_state.gd — add in Project Settings > Globals > Autoload as "GameState".
68extends Node
69
70var score := 0
71signal score_changed(value: int)
72
73func add_score(points: int) -> void:
74 score += points
75 score_changed.emit(score) # any scene can: GameState.score_changed.connect(...)
76```
77
78### 4. Change the running scene
79
80```gdscript
81func go_to_level_2() -> void:
82 # Swaps the current scene for another. Frees the old scene tree.
83 get_tree().change_scene_to_file("res://levels/level_2.tscn")
84 # Or, with a preloaded PackedScene:
85 # get_tree().change_scene_to_packed(LEVEL_2)
86```
87
88## Pitfalls
89
90- **`$Path` / `get_node()` return `null` or error** when the path is wrong or the node
91 isn't in the tree yet. Use `@onready`, verify the path matches the scene, or use
92 `get_node_or_null()` for optional nodes.
93- **Renaming a node breaks `$Path`.** Use **unique names** (`%Name`, set via right-click
94 > Access as Unique Name) so deep references survive renames and reparenting.
95- **`free()` mid-frame can crash** other code still using the node. Prefer
96 `queue_free()` (deletes at end of frame) and check `is_instance_valid(node)`.
97- **Setting child state before `add_child()`** is fine, but `_ready()` on the child only
98 runs _after_ it enters the tree — don't expect its `@onready` vars before that.
99- **Autoload order matters**: autoloads are added before the main scene, in list order.
100 An autoload can't depend on the main scene existing yet.
101- **`instance()` was renamed** to `instantiate()` in Godot 4. `preload` runs at parse
102 time (path must be constant); `load` runs at runtime (path can be a variable).
103- **`change_scene_to_file()` is deferred**, not immediate — Godot swaps and frees the old
104 scene at the end of the current frame. Any code after the call still runs against the _old_
105 tree, and `get_tree().current_scene` isn't the new scene until next frame. Don't read the new
106 scene's nodes on the same line; do it from the new scene's `_ready()`.
107
108## References
109
110- For scene inheritance, `owner`/ownership when saving scenes from code, groups vs
111 unique names, and node-path edge cases, read `references/tree-and-instancing.md`.
112
113## Related skills
114
115- `godot-gdscript` — language, lifecycle, and `@onready`.
116- `godot-signals-groups` — decouple instanced scenes from their spawner.
117- `godot-resources` — share data between instances without duplicating it.
118- `save-systems` — persist scene/game state across runs.