CollectionService
成员函数
| 给节点增加标签 |
| 移除节点标签 |
| 获取该标签的所有节点 |
| 获取该节点的所有标签 |
| 该节点是否有标签 |
代码示例
lua
-- CollectionService 用于给节点打上标签, 不同的标签, 方便对节点进行管理
-- 解决问题:
-- 因为 Studio 内节点是流式加载, 想要收集内所有的特定类型的节点异常的复杂
-- 一些纯表现效果, 直接客户端实现, 减少同步的内容, 减少主机卡顿
-- 给特定类型的节点显示名字, 不用CollectionService的做法为, UIRoot3D 只能在主机创建, 以便于同步给所有的玩家看见
-- 可以使用 CollectionService 变成客机自己创建
-- 主机代码:
-- 创建一个怪物模型
local CollectionService = game:GetServices("CollectionService")
function CreateMonsterModel(name)
local monster = SandboxNode.new("Model", game.Workspace)
monster.ModelId = ...
monster:SetAttribute("Name", name)
monster:SetAttribute("EffectId", 10)
-- 为节点添加标签, 对于 clone 出来的节点, 也可以在 studio 提前编辑好
CollectionService:AddLabel("AddNameHud", monster) -- 所有客机为这个节点创建名字头显示
CollectionService:AddLabel("AddEffect", monster) -- 所有客机为这个节点添加特效
end
CreateMonsterModel("大Boss")
CreateMonsterModel("小怪")
-- 客机代码:
-- 注册所有的Label处理函数
local function RegisterLabelFunction(label, func)
for _, node in ipairs(CollectionService:GetLabeled(label)) do -- 先获取所有拥有这个 Label 的节点执行
func(node)
end
CollectionService:GetNodeAddedNotify(label):Connect(function(node) -- 注册这个 Label 的节点添加事件
func(node)
end)
end
-- 为每个拥有 AddNameHud Label 的节点添加名称
local function AddNameHudHandler(node)
local name = node:GetAttribute("Name")
local hud = SandboxNode.new("UIRoot3D", node)
hud.LocalPosition = Vector2.new(0, 200, 0)
local txt = SandboxNode.new("UILabel", hud)
txt.Title = name
end
RegisterLabelFunction("AddNameHud", AddNameHudHandler)
-- 为每个拥有 AddEffect Label 的节点添加特效
local function AddEffectHandler(node)
local effectId = node:GetAttribute("EffectId")
local effectObj = SandboxNode.new("DefaultEffect, node)
effectObj.EffectIndex = effectId
end
RegisterLabelFunction("AddEffect", AddEffectHandler)