module
Lapis::Docs::C_GAMEPLAY_AND_DECLARATIVE_DSL::E_SCENE_TREE_AND_LIFECYCLE
Overview
Scene Tree Manipulation & Node Lifecycle
Comprehensive guide to navigating the Godot SceneTree, instantiating nodes, understanding native C++ memory ownership rules, and preventing memory leaks.
Executive Summary & Key Topics
| Topic | Method / Anchor | Description |
|---|---|---|
| The Two Node Ownership Rules | .topic_00_ownership_rules |
Tree-owned nodes (queue_free) vs standalone unparented nodes (manual .destroy). |
| Instantiating Nodes Programmatically | .topic_01_creating_nodes |
Using Godot.create to allocate typed engine nodes and adding to the tree. |
| Changing Scenes & Tree Queries | .topic_02_changing_scenes |
Accessing the active tree, changing scenes, and finding nodes by path. |
Related Guides & Source References
- Scene Tree Extensions:
src/libgodot/extensions/scene_tree.cr - Live Specs:
spec/suites/test_scene_tree.cr - Ergonomic Node & Path Access:
Lapis::Docs::C_GAMEPLAY_AND_DECLARATIVE_DSL::G_ERGONOMIC_NODE_ACCESS
Defined in:
libgodot/docs/c_gameplay_and_declarative_dsl/e_scene_tree_and_lifecycle.crClass Method Summary
-
.topic_00_ownership_rules : Nil
The Two Node Ownership Rules: Tree-owned nodes (queue_free) vs standalone unparented nodes (manual .destroy).
-
.topic_01_creating_nodes : Nil
Instantiating Nodes Programmatically: Using Godot.create to allocate typed engine nodes and adding to the tree.
-
.topic_02_changing_scenes : Nil
Changing Scenes & Tree Queries: Accessing the active tree, changing scenes, and finding nodes by path.
Class Method Detail
The Two Node Ownership Rules: Tree-owned nodes (queue_free) vs standalone unparented nodes (manual .destroy).
Key Topics & Information
- Rule 1: Nodes added to the scene tree (add_child) are owned by Godot; call queue_free
- Rule 2: Standalone unparented nodes created via Godot.create are owned by Crystal; call .destroy
- Rule 3: RefCounted and Resource objects are managed atomically; never call .destroy
Instantiating Nodes Programmatically: Using Godot.create to allocate typed engine nodes and adding to the tree.
# 1. Create a typed node instance
bullet = Godot.create(Godot::Sprite2D)
bullet.texture = bullet_texture
bullet.position = position
# 2. Add to active scene tree (tree assumes ownership)
get_parent.not_nil!.add_child(bullet)
# 3. Queue deletion at end of frame
bullet.queue_free
Changing Scenes & Tree Queries: Accessing the active tree, changing scenes, and finding nodes by path.
# Access global SceneTree:
tree = get_tree
# Change to another scene file:
tree.change_scene_to_file("res://scenes/level_02.tscn")
# Finding child nodes ergonomically:
if hud = self[Godot::Control, "CanvasLayer/HUD"]?
hud.visible = true
end