Groups & Tree Queries
A group is a tag on a node. A node can be in any number of groups, and the SceneTree keeps an index of every group, so "all enemies", "everything that must be saved" or "the player" are one call away, without hard-coded paths and without holding references to nodes that might be freed.
Typical groups: enemies, player, pickups, persist (save me), damageable, pausable, interactable.
Adding nodes to groups
In the editor:
- Select a node and open the Node dock (next to the Inspector), then the Groups tab.
- Type a name and click Add. Tick Persistent if you want the group stored in the scene file (it then shows up in
.tscnfiles asgroups=["enemies"]). - Recent 4.x versions also have Project Settings > Global Groups, where you define group names (with a description) once for the whole project, so they appear in every node's group list.
[node name="Slime" type="CharacterBody2D" parent="." groups=["enemies"]]In code: add_to_group("enemies"), remove_from_group("enemies"), is_in_group("enemies"). Adding the group in the enemy's own script (in _ready) is a good habit: every instance of the scene is tagged automatically and nobody can forget it.
Querying and calling groups
extends Node
# frames: 1
class Enemy extends Node:
var hp := 3
func _ready():
add_to_group("enemies")
func take_damage(amount: int) -> void:
hp -= amount
print(" ", name, " hp ", hp)
if hp <= 0:
queue_free()
func alert(where: Vector2) -> void:
print(" ", name, " heads to ", where)
func _ready():
for n in ["Slime", "Bat", "Ghost"]:
var e := Enemy.new()
e.name = n
add_child(e)
var player := Node.new()
player.name = "Player"
player.add_to_group("player")
add_child(player)
get_node("Bat").hp = 1
var tree := get_tree()
print("enemies: ", tree.get_nodes_in_group("enemies").map(func(e): return String(e.name)))
print("count: ", tree.get_node_count_in_group("enemies"))
print("player: ", tree.get_first_node_in_group("player").name, ", is Bat an enemy? ", $Bat.is_in_group("enemies"))
print("call_group alert:")
tree.call_group("enemies", "alert", Vector2(10, 20))
print("bomb hits everyone for 1:")
tree.call_group("enemies", "take_damage", 1)
print("Bat still in tree this frame: ", has_node("Bat"))
print("no boss: ", tree.get_first_node_in_group("bosses") == null)
func _process(_delta):
print("next frame, enemies: ", get_tree().get_nodes_in_group("enemies").map(func(e): return String(e.name)))enemies: ["Slime", "Bat", "Ghost"]
count: 3
player: Player, is Bat an enemy? true
call_group alert:
Slime heads to (10.0, 20.0)
Bat heads to (10.0, 20.0)
Ghost heads to (10.0, 20.0)
bomb hits everyone for 1:
Slime hp 2
Bat hp 0
Ghost hp 2
Bat still in tree this frame: true
no boss: true
next frame, enemies: ["Slime", "Ghost"]
What the run shows:
get_nodes_in_group()returns a freshArrayof nodes in tree order. It is a copy, so freeing nodes while you loop over it is safe.get_first_node_in_group("player")is the clean way to find a single special node from anywhere. It returnsnullwhen the group is empty: check it, the player may be dead or not spawned yet.call_group(group, method, args...)calls the method on every member that has it; members without the method are skipped silently. That makes it easy to use and easy to misspell: a typo calls nothing and reports nothing.queue_free()waits until the end of the frame, so the Bat is still in the tree (and in the group) for the rest of this frame, and gone in the next. Freed nodes leave their groups automatically.
Related calls: call_group_flags(SceneTree.GROUP_CALL_DEFERRED, ...) defers the calls to the end of the frame (safe when the calls add or free nodes), set_group(group, property, value) sets a property on every member, and notify_group() sends a notification.
A save system built on a group
Groups make a simple, decoupled save system: every node that wants to be saved joins persist and implements save_state() and load_state(). The save manager doesn't need to know what a chest or a door is.
extends Node2D
# frames: 0
class Chest extends Node2D:
var opened := false
func save_state() -> Dictionary:
return {"path": String(get_path()), "opened": opened}
func load_state(d: Dictionary) -> void:
opened = d.opened
func _ready():
for i in 3:
var c := Chest.new()
c.name = "Chest%d" % i
c.add_to_group("persist")
add_child(c)
$Chest1.opened = true
var saved: Array = get_tree().get_nodes_in_group("persist").map(func(n): return n.save_state())
print(JSON.stringify(saved))
# New session: everything closed again, then restore
for c in get_tree().get_nodes_in_group("persist"):
c.opened = false
for d in saved:
get_node(NodePath(d.path)).load_state(d)
print("after load: ", get_tree().get_nodes_in_group("persist").map(func(n): return n.opened))
$Chest2.remove_from_group("persist")
print("persist now: ", get_tree().get_node_count_in_group("persist"))
get_tree().set_group("persist", "visible", false)
print("Chest0 visible: ", $Chest0.visible, ", Chest2 visible: ", $Chest2.visible)[{"opened":false,"path":"/root/Main/Chest0"},{"opened":true,"path":"/root/Main/Chest1"},{"opened":false,"path":"/root/Main/Chest2"}]
after load: [false, true, false]
persist now: 2
Chest0 visible: false, Chest2 visible: true
Storing the node path works for nodes placed in the level. For nodes spawned at runtime (dropped items, enemies), also store the scene file path (scene_file_path) and the position, and instantiate them again on load. Write the array to disk as shown in Saving.
Groups or something else?
| Need | Use |
|---|---|
| "All X in the level", broadcast to many | groups |
| One node reacting to another's event | a signal |
| A node's own child | $Child or %UniqueName (calls down) |
| Global state that lives across scenes | an autoload (Project Settings & Autoloads) |
| Is the thing I touched an enemy? | body.is_in_group("enemies") in a collision callback |
Tip: Keep group names in one place, for example constants in an autoload (
const ENEMIES := &"enemies") or the Global Groups list. A misspelt group name is a silent bug: the query just returns an empty array.
get_nodes_in_group is fast, but calling it for every enemy, every frame, adds up. When a system needs the list constantly, keep its own array up to date with signals instead, or query once per frame and share the result.
Test yourself
What does get_tree().call_group("enemies", "alert", pos) do with a member that has no alert method?
- Crashes the game
- Skips it silently
- Removes it from the group
- Prints a parse error
Right after enemy.queue_free(), is the enemy still returned by get_nodes_in_group("enemies") in the same frame?
- No, it is removed instantly
- Yes; queued nodes are freed at the end of the frame and leave their groups then
- Only if it was added in the editor
- It returns null in its place
What is the cleanest way for an enemy to find the player without a hard-coded node path?
get_node("/root/Level/Player")get_tree().get_first_node_in_group("player"), checking for null- A global variable set in every scene
find_child("Player")on the root every frame