Up to date

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

Skupiny

Groups in Godot work like tags in other software. You can add a node to as many groups as you want. Then, in code, you can use the SceneTree to:

  • Get a list of nodes in a group.

  • Call a method on all nodes in a group.

  • Send a notification to all nodes in a group.

This is a useful feature to organize large scenes and decouple code.

Managing groups

Groups are created by adding a node to a new group name, and likewise they are removed by removing all nodes from a given group.

Existují dva způsoby přidávání/odebírání uzlů do skupin:

Použití doku uzlu

You can add nodes in the current scene to groups using the Groups tab in the Node dock.

../../_images/groups_node_tab.webp

Select one or more nodes in the Scene dock and write the group name in the field, then click Add.

../../_images/groups_add_node_to_group.webp

You should now see the group appear.

../../_images/groups_node_after_adding.webp

In a complex project, you may end up with many groups or large scenes with many nodes. You can add or remove any node to groups using the Group Editor window. To access it, click the Manage Groups button.

../../_images/groups_manage_groups_button.webp

The Group Editor window appears. Here's a screenshot from a complex project to illustrate the tool's purpose.

../../_images/groups_group_editor_window.webp

It has three columns:

  1. A list of groups used by nodes in the current scene.

  2. A list of nodes that are not part of the selected group.

  3. A list of nodes in the group.

The fields at the bottom allow you to add new groups or filter nodes in the second and third columns.

Poznámka

Any node name that's greyed out means the node was added to the group in a different scene and you cannot edit it here. This happens on scene instances in particular.

Pomocí kódu

Skupiny můžete spravovat také ze skriptů. Následující kód přidá uzel, ke kterému připojíte skript, do skupiny guards, jakmile vstoupí do stromu scény.

func _ready():
    add_to_group("guards")

Imagine you're creating an infiltration game. When an enemy spots the player, you want all guards and robots to be on alert.

In the fictional example below, we use SceneTree.call_group() to alert all enemies that the player was spotted.

func _on_player_spotted():
    get_tree().call_group("guards", "enter_alert_mode")

Výše uvedený kód volá funkci enter_alert_mode u každého člena skupiny strážců.

Je také možné získat úplný seznam uzlů nepřátel voláním SceneTree.get_nodes_in_group ():

var guards = get_tree().get_nodes_in_group("guards")

Třída SceneTree poskytuje mnoho dalších užitečných metod pro práci se scénami, jejich hierarchií uzlů a skupinami. Umožňuje snadno přepínat scény nebo je znovu načítat, ukončovat hru nebo ji pozastavovat a rušit. Poskytuje také užitečné signály.