主题
Camp
概览
| 字段 | 值 |
|---|---|
| Kind | Data · 数据 Data |
| Realm | common |
Camp 表示游戏中的一个阵营,用于聚合同阵营的玩家并观察成员变化。通过 GetPlayers 返回的迭代器遍历当前阵营玩家,并通过 PlayerAdded、PlayerRemoved 监听成员加入或离开。
适用场景
在需要按阵营区分玩家时使用,例如从 game:GetService("Camps") 调用 GetCamps() 取出全部阵营,逐个遍历成员来完成分组、队伍展示或基于阵营的判定逻辑。
使用要点
通过 ipairs(Camps:GetCamps()) 遍历当前全部阵营;拿到 Camp 后,把 camp:GetPlayers() 直接用于泛型 for 遍历玩家,并可监听 PlayerAdded/PlayerRemoved。
注意事项
Camp 来自 Camps:GetCamps() 返回的 Camp 数组,不直接构造。GetPlayers 返回 Lua 迭代器,应写成 for _, player in camp:GetPlayers() do,不能对返回值使用 ipairs、# 或下标访问。
代码示例
通过 Camps 服务读取阵营玩家
lua
-- @runtime client
local Camps = game:GetService("Camps")
local camp = Camps:GetCamps()[1]
if camp == nil then return end
for _, player in camp:GetPlayers() do
print("阵营玩家:", player.Name)
end事件 (2)
PlayerAdded
签名:PlayerAdded(player: Player) 触发:local
Camp 的 PlayerAdded 事件,当有玩家加入该阵营时触发,回调会收到一个 Player 类型参数,代表加入阵营的玩家。
| 回调参数 | 类型 | 说明 |
|---|---|---|
player | Player | 玩家 |
示例代码
监听玩家加入阵营
lua
-- @runtime client
local Camps = game:GetService("Camps")
local camp = Camps:GetCamps()[1]
if camp == nil then return end
camp.PlayerAdded:Connect(function(player)
print("玩家加入阵营:", player.Name)
end)PlayerRemoved
签名:PlayerRemoved(player: Player) 触发:local
Camp 的 PlayerRemoved 事件,当有玩家离开该阵营时触发,回调会收到一个 Player 类型参数,代表离开阵营的玩家。
| 回调参数 | 类型 | 说明 |
|---|---|---|
player | Player | 玩家 |
示例代码
监听玩家离开阵营
lua
-- @runtime client
local Camps = game:GetService("Camps")
local camp = Camps:GetCamps()[1]
if camp == nil then return end
camp.PlayerRemoved:Connect(function(player)
print("玩家离开阵营:", player.Name)
end)函数 (1)
GetPlayers
签名:GetPlayers() -> Function (阵营玩家列表)
返回用于遍历当前阵营玩家的 Lua 迭代器,应直接用于泛型 for。
返回值 Function (阵营玩家列表)
示例代码
遍历 Camp 的玩家
lua
-- @runtime client
local Camps = game:GetService("Camps")
local camp = Camps:GetCamps()[1]
if camp == nil then return end
local playerCount = 0
for _ in camp:GetPlayers() do playerCount = playerCount + 1 end
print("阵营玩家数:", playerCount)