代码示例
集合生命周期和事件
local CollectionService = game:GetService("CollectionService")
-- 一个实时的部件集合,标记为 "MapleLeaf",是标记为 "MapleTree" 的模型的直接子项
local mapleLeaves: Collection = CollectionService:CreateCollection("Model.MapleTree > Part.MapleLeaf")
local function sway(leaf: Part, deltaTime: number)
leaf.CFrame *= CFrame.fromEulerAnglesXYZ(0, math.rad(20) * deltaTime, 0)
end
local function fall(leaf: Part)
leaf.Anchored = false
end
-- OnAdded 对于每个已经匹配的叶子触发一次,然后对于每个新的匹配触发
function mapleLeaves.OnAdded(leaf: Part)
leaf.Material = Enum.Material.Neon
end
-- OnRemoved 在叶子停止匹配时触发(未标记、重新父级到树外或被销毁)
function mapleLeaves.OnRemoved(leaf: Part)
leaf.Material = Enum.Material.Plastic
end
-- RunService 回调:每个心跳对集合中的每个叶子触发一次
function mapleLeaves.OnHeartbeat(leaf: Part, deltaTime: number)
sway(leaf, deltaTime)
end
-- 事件回调:连接到每个叶子的 BasePart.Touched
function mapleLeaves.OnTouched(leaf: Part, other: BasePart)
fall(leaf)
end
-- 属性回调:当叶子的颜色变化时触发
function mapleLeaves.OnPropertyChanged.Color(leaf: Part)
if leaf.Color == Color3.fromRGB(124, 92, 70) then
fall(leaf)
end
end
-- 将当前集合中的每个叶子设置为绿色
mapleLeaves:ForEach(function(leaf: Part)
leaf.Color = Color3.fromRGB(0, 255, 0)
end)API 参考
属性
方法
Destroy
Collection:Destroy()