Up to date

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

Grupos

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.

Gerenciando grupos

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.

Há duas maneiras de acrescentar/remover nós aos grupos:

Usando o painel do nó

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.

Nota

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.

Usando código

Você também pode administrar grupos a partir de scripts. O seguinte código adiciona o nó ao qual você anexa o script ao grupo guards assim que ele entra na árvore de cena.

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")

O código acima chama a função enter_alert_mode em cada membro do grupo guards.

Para obter a lista completa de nós no grupo guards como uma matriz, você pode chamar SceneTree.get_nodes_in_group():

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

A classe SceneTree fornece muitos métodos úteis para interagir com cenas, suas hierarquias e grupos de nós. Ela lhe permite facilmente trocar ou recarregar cenas, sair do jogo ou pausa-lo ou retomá-lo. Ela também fornece sinais úteis.