分组
Godot 中的分组与其他软件中的标签类似。你可以将节点加入若干个分组之中,然后在代码中通过 SceneTree 来:
获取某个分组中的节点列表。
对分组中的所有节点调用方法。
向分组中的所有节点发送通知。
这个功能可以用来组织大型场景、解耦代码。
管理分组
将节点添加到一个新的分组名称中即可创建分组,同样,将所有节点移出某个给定的分组即可移除分组。
为分组添加/移除节点有两种方法:
During design, by using the Node dock in the editor, or the Global Groups in project settings.
运行模式下,调用 Node.add_to_group() 或 Node.remove_from_group()方法。
使用节点面板
You can create new groups using the Groups tab in the Node dock.
Select one or more nodes in the Scene dock then click the add button with the + symbol.
You should now see the Create New Group modal appear. Write the group name in the field.
You can optionally mark the option “Global”, which will make the group visible project-wide, and able to be reused in any project scene. This will also allow you to give it a description.
When done, press Ok to create it.
You should see the new groups appear in the Groups tab under Scene Groups if the Global option was unmarked, or under Global Groups if that option was marked.
Selected Node(s) from the Scene dock can be added into groups by marking the checkbox on the left side of the groups in the Groups dock. The node(s) you had selected when creating a new group will be automatically checked.
All groups present in the project that were marked as Global, created from any scene, will be visible under Global Groups.
Any other group derived from nodes in the current scene will appear under Scene Groups.
警告
The same underlying logic is used for both Global and Scene groups. Groups with the same name are considered one and the same. This feature is purely organizational.
You can manage Global Groups in the Global Groups dock, inside Project Settings. There, you will be able to add new global groups, or change existing groups’ names and descriptions.
使用代码
你也可以通过脚本来管理分组。以下代码会在脚本所附加的节点进入场景树时,将其加入 guards
(守卫)分组。
GDScriptC#
func _ready():
add_to_group("guards")
public override void _Ready()
{
base._Ready();
AddToGroup("guards");
}
想象一下你正在制作一个潜入类游戏,敌人发现玩家后,希望所有守卫和机器人都进入警觉状态。
下面的例子中,我们使用 SceneTree.call_group()
来通知所有敌人:玩家被发现了。
GDScriptC#
func _on_player_spotted():
get_tree().call_group("guards", "enter_alert_mode")
public void _OnPlayerDiscovered()
{
GetTree().CallGroup("guards", "enter_alert_mode");
}
以上代码会对 gurads
分组中的所有成员节点调用 enter_alter_mode
函数。
要获取由 guards
分组中的所有节点所构成的数组,请调用 SceneTree.get_nodes_in_group():
GDScriptC#
var guards = get_tree().get_nodes_in_group("guards")
var guards = GetTree().GetNodesInGroup("guards");
SceneTree 类提供了许多有用的方法,例如与场景、场景节点层次结构及节点编组交互,还可以使你可以轻松切换场景或重新加载场景、退出游戏或暂停和恢复运行游戏。不仅如此,该类还提供了一些有用的信号。