一个 玩家 对象是当前连接的客户端。当新玩家连接时,这些对象被添加到 Players 服务,然后当他们最终断开服务器时被移除。
Instance.Name 属性反映了玩家的用户名。当保存有关玩家的信息时,你应该使用他们的 Player.UserId 因为有可能玩家会更改他们的用户名。
在 Players 服务中有几种类似方法用于与玩家对象工作。使用它们超过其各自的 Instance 方法:
- 你可以使用 Players:GetPlayers() 获取当前玩家对象的表;再次使用这个而不是 Instance:GetChildren() 。
- 同样,你可以使用 检测玩家对象的移除,该操作在玩家被移除之前(而不是之后)触发。如果您正在保存可能在移除时删除或清理的玩家信息,这很重要。
代码示例
This code sample demonstrates the creation of leaderboard stat values in Roblox's default player list UI. It creates a "Score" leaderstat that starts at 0.
local Players = game:GetService("Players")
local function onPlayerAdded(player)
-- Create a container for leaderstats
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
-- Create one leaderstat value
local vScore = Instance.new("IntValue")
vScore.Name = "Score"
vScore.Value = 0
vScore.Parent = leaderstats
-- Add to player (displaying it)
leaderstats.Parent = player
end
Players.PlayerAdded:Connect(onPlayerAdded)
概要
属性
描述玩家的帐户年龄以天为单位。
决定使用移动设备的玩家角色在撞击障碍物时是否自动跳跃。
玩家的相机允许缩小放的最大距离。
玩家的相机允许放大放的最小距离。
将相镜头模式更改为第一或第三人称。
决定角色是否在玩家生成时加载。如果为 false,玩家将生成默认外观。
确定使用角色外观的帐户用户 ID,其用于玩家的 character 。
设置默认相机如何处理在相机和玩家之间的对象。
决定使用 Roblox 桌面版时玩家的相机移动模式。
决定使用 Roblox 桌面版时玩家的角色移动模式。
决定玩家是否可以切换鼠标锁定。
决定使用触摸设备时玩家的相机移动模式。
决定使用触摸设备时玩家的角色移动模式。
与玩家关联的用户ID的显示名称。
描述玩家跟随玩家进入游戏的玩家用户 ID。
是否暂停玩家端游戏。
指示玩家是否拥有验证徽章。
设置此玩家可以看到其他机器人的生命条的距离。如果设置为 0,生命条将不会显示。
此属性显示了本地玩家为其 Roblox 帐户设置的本地 ID。
描述帐户的会员输入。
设置此玩家可以看到其他机器人的名称的距离。如果设置为 0,名称将被隐藏。
决定玩家是否在特定团队上。
将零件设置为围绕复制聚焦。
如果设置,玩家将在指定的 SpawnLocation 重生。
确定玩家与哪个团队关联。
确定玩家与哪个团队关联。
一个唯一的识别整数,分配给所有用户帐户。
方法
从玩家角色中移除所有饰品和其他角色外观对象。
返回角色头和给定的 Vector3 点之间的距离。如果玩家没有角色,返回 0。
返回包含描述如何加入体验的信息的词典Player的列表
返回客户端使用的鼠标。
返回隔离网络延迟在秒内。
返回玩家角色的外观是否已加载。
返回玩家是否使用具体、实世信号进行验证。
强行从游戏中断玩家,可选提供消信息。
使玩家的角色在指定方向上走动,直到被停止或由玩家中断(通过使用其控制件)。
设置玩家的帐户年龄。
设置玩家是否看到过滤的聊天,而不是普通的聊天。
返回在线朋友的词典。
返回玩家在群组中的排名作为一个整数,介于 0 和 255 之间,其中 0 是非成员,255 是群组的所有者。
将玩家在群组中的角色返回为字符串,或“访客”如果玩家不是群组的一部分。
检查玩家是否是用户的朋友,使用给定的 Player.UserId 。
检查玩家是否是给定ID的组成员。
生成一个虚拟形象,使其具备传递到 HumanoidDescription 中的所有装备。
服务器向玩家发送到指定位置的请求。
活动
当玩家角色生成或重生时发射。
当全部外观的 Player.Character 已插入时发生火焰。
在玩家的角色被移除之前发射。
当玩家使用 Roblox 提供的聊天栏在游戏中聊天时,发生火灾。
此事件发生大约两分钟后,游戏引擎将 player 分类为闲置。时间是自那一刻起已过的秒数。
当玩家的传送状态发生变化时,发射。
属性
AccountAge
帐户年龄是一个描述玩家帐户多久前注册的日期的 Player 属性。它使用 Player:SetAccountAge() 函数设置,不能通过脚本访问。
此属性有用于条件地显示新的 Roblox 玩家内容,例如教程。
代码示例
This code sample adds a mark to players showing about how old their account is. The mark uses a player's account age to determine if they are a New Player, Veteran Player or Regular Player.
local Players = game:GetService("Players")
local MAX_AGE_NEW_PLAYER = 7 -- one week
local MIN_AGE_VETERAN = 365 -- one year
-- This function marks a part with text using a BillboardGui
local function mark(part, text)
local bbgui = Instance.new("BillboardGui")
bbgui.AlwaysOnTop = true
bbgui.StudsOffsetWorldSpace = Vector3.new(0, 2, 0)
bbgui.Size = UDim2.new(0, 200, 0, 50)
local textLabel = Instance.new("TextLabel")
textLabel.Size = UDim2.new(1, 0, 1, 0) -- Fill parent
textLabel.Text = text
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.BackgroundTransparency = 1
textLabel.Parent = bbgui
-- Add to part
bbgui.Parent = part
bbgui.Adornee = part
end
local function onPlayerSpawned(player, character)
local head = character:WaitForChild("Head")
if player.AccountAge >= MIN_AGE_VETERAN then
mark(head, "Veteran Player")
elseif player.AccountAge <= MAX_AGE_NEW_PLAYER then
mark(head, "New Player")
else
mark(head, "Regular Player")
end
end
local function onPlayerAdded(player)
-- Listen for this player spawning
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
AutoJumpEnabled
AutoJumpEnabled 属性决定是否使用移动设备的 在碰到障碍物时自动跳跃。这可以在移动设备上使级别更易于导航。
当玩家加入游戏时,StarterPlayer.AutoJumpEnabled决定了此属性的初始状态。然后,这个属性决定了 Humanoid.AutoJumpEnabled 属性的值在生重生点时的 Player.Character 值。换言之,使用这三个属性可以在每个角色、每个玩家和每场游戏的基础上设置自动跳转行为。
代码示例
This code sample is meant for a TextButton. It allows the player to toggle the auto-jumping behavior while on a mobile device.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local button = script.Parent
local function update()
-- Update button text
if player.AutoJumpEnabled then
button.Text = "Auto-Jump is ON"
else
button.Text = "Auto-Jump is OFF"
end
-- Reflect the property in the player's character, if they have one
if player.Character then
local human = player.Character:FindFirstChild("Humanoid")
if human then
human.AutoJumpEnabled = player.AutoJumpEnabled
end
end
end
local function onActivated()
-- Toggle auto-jump
player.AutoJumpEnabled = not player.AutoJumpEnabled
-- Update everything else
update()
end
button.Activated:Connect(onActivated)
update()
CameraMaxZoomDistance
CameraMaxZoomDistance Player 属性设置相机最大距离可以从默认相机与角色的最大距离以学分。
换言之,它控制玩家的相机最大允许缩小距离。
该属性的默认值由 StarterPlayer.CameraMaxZoomDistance 设置。如果这个值设置为 Player.CameraMinZoomDistance 的更低值,它将增加到相机的最小缩放距离。
代码示例
The example demonstrates how to set a player's camera minimum and maximum zoom distance.
In this example, we set the Player.CameraMinZoomDistance and Player.CameraMaxZoomDistance to set the min and max distance in studs a player's camera can be from their character.
Note that since the example attempts to set the CameraMinZoomDistance to be greater than the CameraMaxZoomDistance, the CameraMinZoomDistance value will be decreased and set to the value of the max zoom distance.
To change the default min and max zoom distance values for a player when they first enter the game, you can change the StarterClass.Player.CameraMinZoomDistance and StarterClass.Player.CameraMaxZoomDistance properties.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75
CameraMinZoomDistance
CameraMinZoonDistance Player 属性设置了相机可以从默认相机与角色的最小距离以学分。
换言之,它控制玩家的相机允许缩放的最小距离。
该属性的默认值由 StarterPlayer.CameraMinZoomDistance 设置。如果这个值设置为高于 Player.CameraMaxZoomDistance 的值,它将被减少为 CameraMaxZoomDistance。
代码示例
The example demonstrates how to set a player's camera minimum and maximum zoom distance.
In this example, we set the Player.CameraMinZoomDistance and Player.CameraMaxZoomDistance to set the min and max distance in studs a player's camera can be from their character.
Note that since the example attempts to set the CameraMinZoomDistance to be greater than the CameraMaxZoomDistance, the CameraMinZoomDistance value will be decreased and set to the value of the max zoom distance.
To change the default min and max zoom distance values for a player when they first enter the game, you can change the StarterClass.Player.CameraMinZoomDistance and StarterClass.Player.CameraMaxZoomDistance properties.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75
CameraMode
相机模式 属性设置玩家的相机模式,默认为第三人称。
第三人称
在默认的第三人称模式(Enum.CameraMode.Classic)中,角色可以在相镜头中看到。在这种模式下,默认行为是:
- 玩家可以右键单击并拖动(鼠标)、点击并拖动(移动)、使用副摇杆(游戏手柄)或按下左/右箭头(键盘)来在角色周围旋转相机。
- 当玩家移动角色时,它面向相应的移动方向。
- 玩家可以自由缩放,甚至在全部缩放时变为第一人称视角。
第一人称
在第一人称模式(Enum.CameraMode.LockFirstPerson)下,玩家的相机始终处于缩放状态。除非具有可见的 GUI 与 GuiButton.Modal 属性设置为 true , 移动鼠标、在移动设备上拖动或使用游戏手柄上的副拇指将旋转相机围绕角色。
代码示例
This example demonstrates how to change the character's CameraMode to first person using the LockFirstPerson value of the Enum.CameraMode enum.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMode = Enum.CameraMode.LockFirstPerson
CanLoadCharacterAppearance
CanLoadCharacterAppearance Player 属性决定角色的外观在玩家生成时是否会加载。该属性的默认值由 StarterPlayer.LoadPlayerAppearance 设置。
如果 true,角色将加载对应玩家的 Player.CharacterAppearanceId 的外观。
如果 为 false,玩家将生成默认外观 - 没有任何帽子、衬衫、裤子等的灰色角色模型
将属性设置在角色生成后不会更改角色,您必须调用 Player:LoadCharacter() 加载新的外观。
代码示例
This example demonstrates how to disable loading a player's character appearance. Instead, the player loads as a grey model without any hats, shirts, pants, etc.
This is useful for games using custom clothing and accessories.
Note that if the character has already spawned, this change will not take affect until the player respawns or the Player:LoadCharacter() function is called.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CanLoadCharacterAppearance = false
Character
角色 属性包含一个指向包含Model、身体部位、脚本和其他对象的Humanoid的引用,用于模拟玩家在体验中的虚拟形象。模型属于 Workspace 但可以移动。当 Players.CharacterAutoLoads 是 true 时,它会自动加载,否则可以手动加载,使用 Player:LoadCharacter() 。
最初这个属性是 nil ,当玩家角色第一次生成时设置。使用 Player.CharacterAdded 事件检测玩家角色正确加载时,以及 Player.CharacterRemoving 事件检测角色即将被销毁时。避免在此属性上使用 Object:GetPropertyChangedSignal()。
请注意,从 或 克隆到玩家的 或 中的 或 通常会在旧角色模型被替换之前运行,因此 可能会指向旧模型的 属性。因此,在 LocalScript 下 StarterGui 或 StarterPack 中,建议在使用之前确保 角色 的父不是 nil ,例如:
local Players = game:GetService("Players")local player = Players.LocalPlayerlocal character = player.Characterif not character or character.Parent == nil thencharacter = player.CharacterAdded:Wait()end
CharacterAppearanceId
该属性决定了角色外观用于玩家的 character 的帐户的用户ID。默认情况下,此属性是 Player.UserId ,它使用玩家在 Roblox 网站上创建的虚拟形象。
将此属性更改为另一个帐户的用户 ID 会导致玩家以该帐户的外观(帽子、衬衫、裤子等)重生。
游戏还可以通过修改 StarterPlayer.LoadCharacterAppearance 属性来切换玩家角色的外观是否在游戏中加载。
代码示例
This code sample allows players to chat "/disguise xyz", where xyz is a user ID or username, and they will respawn appearing like that account's avatar. Try typing "/disguise 261" or "/disguise Shedletsky"!
local Players = game:GetService("Players")
local disguiseCommand = "/disguise "
local function onPlayerChatted(player, message)
if message:sub(1, disguiseCommand:len()):lower() == disguiseCommand:lower() then
local input = message:sub(disguiseCommand:len() + 1)
local id = tonumber(input)
if not id then -- Number failed to parse, maybe they typed a username instead
pcall(function() -- This call can fail sometimes!
id = Players:GetUserIdFromNameAsync(input) -- Fetch ID from name
end)
end
if id then
-- Set character appearance then respawn
player.CharacterAppearanceId = id
player:LoadCharacter()
else
-- We couldn't get an ID from their input
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
DevCameraOcclusionMode
定义默认相机脚本如何处理相机和相机主题之间的对象。由 StarterPlayer.DevCameraOcclusionMode 设置,不能为个人玩家更改
默认值为 Zoom (0)。请参阅 Enum.DevCameraOcclusionMode 获取可用模式列表。
DevComputerCameraMode
DevComputerCameraMode 属性决定玩家在使用带有鼠标和键盘的设备时移动相机的方式。查看 Enum.DevComputerCameraMovementMode 以获取每个可用的相机控制模式的描述。此属性不能使用 LocalScript 设置(必须在服务器上使用 Script 来设置)。
该属性的默认值由 StarterPlayer.DevComputerCameraMovementMode 决定。
此属性名称中的“计算机”一词指的是非 TouchEnabled 、非 GamepadEnabled 设备。
当设置为 用户选择 时,玩家可以在 Roblox 游戏设置中选择任何控制模式(除了 可脚本化 )。一通用来说,允许玩家选择控制模式以最大限度地提高可访问性是一个好主意。
设置此属性为 可脚本化 可以创建自定义控制模式。
这个属性不会影响使用触摸启用设备的玩家。请参阅 Player.DevTouchCameraMode 。
代码示例
The example demonstrates how to set a player's camera movement mode for players on a computer.
In this example, we set the camera movement mode to Classic via the Enum.DevComputerCameraMovementMode enum. This means that the camera of players on touch enabled devices will track the player but will not automatically rotate if the player walks left or right.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- Set the player's camera movement mode on computers to classic
player.DevComputerCameraMode = Enum.DevComputerCameraMovementMode.Classic
DevComputerMovementMode
DevComputerMovementMode 属性决定玩家在使用带有鼠标和键盘的设备时移动角色的方式。查看 Enum.DevComputerMovementMode 以获取每个可用的移动控制模式的描述。此属性不能使用 LocalScript 设置(必须在服务器上使用 Script 来设置)。
该属性的默认值由 StarterPlayer.DevComputerMovementMode 决定。
此属性名称中的“计算机”一词指的是非 TouchEnabled 设备。
当设置为 用户选择 时,玩家可以在 Roblox 游戏设置中选择任何控制模式(除了 可脚本化 )。一通用来说,允许玩家选择控制模式以最大限度地提高可访问性是一个好主意。
设置此属性为 可脚本化 可以创建自定义控制模式。
这个属性不会影响使用触摸启用设备的玩家。请参阅 Player.DevTouchMovementMode 。
代码示例
Demonstrates how to set the movement mode for players on computers using the Player.DevComputerMovementMode property.
local Players = game:GetService("Players")
local function onPlayerAdded(player: Player)
-- Set the player's movement mode on desktop devices to click-to-move
-- Once set, the player can right click in the game world and the character will move there.
player.DevComputerMovementMode = Enum.DevComputerMovementMode.ClickToMove
end
Players.PlayerAdded:Connect(onPlayerAdded)
DevEnableMouseLock
该属性决定玩家是否能够通过按下 Mouse 切换锁定 **** 。玩家可以在 Roblox 游戏设置中禁用鼠标锁定开关。默认情况下,此属性设置为 StarterPlayer.EnableMouseLockOption 的值。这可以在运行时通过使用 Script 在服务器端设置。无法在客户端设置。
启用鼠标锁定时,玩家的鼠标指针被锁定在屏幕中心处。移动鼠标将围绕玩家的 character 挑动相机,角色将面向相同的方向,即与 camera 一致。它还抵消了相机视图仅在玩家角色的右肩上。
请注意,与Shift-Lock相关的 API 正在被弃用,因此建议使用 UserInputService.MouseBehavior 来锁定鼠标。
代码示例
This code sample demonstrates how to toggle whether mouse lock is available to a player using a chat command. When a player types "mouselock", their ability to toggle mouse lock is toggled. Note that this does not toggle the actual state of mouse lock; rather, it changes whether a player is able to toggle it themselves.
This code can be run by pasting it into a Script within ServerScriptService.
local Players = game:GetService("Players")
local function toggleMouseLock(player)
player.DevEnableMouseLock = not player.DevEnableMouseLock
if player.DevEnableMouseLock then
print("Mouse lock is available")
else
print("Mouse lock is not available")
end
end
local function onPlayerChatted(player, message, _recipient)
if message == "mouselock" then
toggleMouseLock(player)
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
DevTouchCameraMode
DevTouchCameraMode 属性决定玩家在使用 TouchEnabled 设备时移动相机的方式。参阅Enum.DevTouchCameraMovementMode获取每个可用的相机控制模式的描述。此属性不能使用 LocalScript 设置(必须在服务器上使用 Script 来设置)。
该属性的默认值由 StarterPlayer.DevTouchCameraMovementMode 决定。
当设置为 用户选择 时,玩家可以在 Roblox 游戏设置中选择任何控制模式(除了 可脚本化 )。一通用来说,允许玩家选择控制模式以最大限度地提高可访问性是一个好主意。
设置此属性为 可脚本化 可以创建自定义控制模式。
这个属性不会影响那些没有使用触摸启用设备的玩家。请参阅 Player.DevComputerCameraMovementMode 。
代码示例
The example demonstrates how to set a player's camera movement mode.
In this example, we set the camera movement mode to Classic via the Enum.DevTouchCameraMovementMode enum. This means that the camera of players on touch enabled devices will track the player but will not automatically rotate if the player walks left or right.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- Set the player's camera movement mode on mobile devices to classic
player.DevTouchCameraMovementMode = Enum.DevTouchCameraMovementMode.Classic
DevTouchMovementMode
DevTouchMovementMode 属性决定玩家在使用 TouchEnabled 设备时移动角色的方式。查看 Enum.DevTouchMovementMode 以获取每个可用的移动控制模式的描述。此属性不能使用 LocalScript 设置(必须在服务器上使用 Script 来设置)。
该属性的默认值由 StarterPlayer.DevTouchMovementMode 决定。
当设置为 用户选择 时,玩家可以在 Roblox 游戏设置中选择任何控制模式(除了 可脚本化 )。一通用来说,允许玩家选择控制模式以最大限度地提高可访问性是一个好主意。
设置此属性为 可脚本化 可以创建自定义控制模式。
这个属性不会影响那些没有使用触摸启用设备的玩家。请参阅 Player.DevComputerMovementMode 。
代码示例
The example demonstrates how to set the movement mode for players on touch enabled devices.
In this example, we set the movement mode to Thumbstick via the Enum.DevTouchMovementMode enum. This means that players on touch enabled devices are able to move via a virtual thumbstick on their screen.
local Players = game:GetService("Players")
game.Players.PlayerAdded:Connect(function(player)
-- Set the player's movement mode on mobile devices to a dynamic thumbstick
player.DevTouchMovementMode = Enum.DevTouchMovementMode.DynamicThumbstick
end)
DisplayName
是包含与 对象相关的认证用户显示名称的属性。与用户名不同,显示名称是玩家向他人显示的非唯一名称。如果 Roblox 用户尚未选择任何一个,属性将与 Name 属性相同。
注意:
- 由于显示名称不是唯一的,因此单个实例中的两个玩家可能拥有相同的名称。如果需要为玩家提供全球唯一标识符,请使用 Player.UserId (静态) 或 Player.Name (当前用户名) 而不使用。
- 显示名称可能包含串中的Unicode字符。请参阅UTF-8了解有Unicode字符的字符串如何工作的更多信息。
FollowUserId
跟随用户ID是一个Player属性,包含玩家跟随到游戏的用户的Player.UserId。如果玩家没有跟随任何人进入游戏,该属性将为 0。此属性对于警告那些被另一名玩家跟踪到游戏中的玩家有用。
您可以使用此用户 ID 和 Players:GetNameFromUserIdAsync() 函数跟随玩家的名称。
代码示例
This code sample alerts players if a new player follows the local player into the game. Place this in a LocalScript in StarterPlayerScripts.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local screenGui = Instance.new("ScreenGui")
screenGui.Parent = player:WaitForChild("PlayerGui")
local function onPlayerAdded(newPlayer)
if newPlayer.FollowUserId == player.UserId then
local textLabel = Instance.new("TextLabel")
textLabel.Parent = screenGui
textLabel.Text = "You were followed to this game by " .. newPlayer.Name .. "!"
task.delay(3, function()
if textLabel then
textLabel:Destroy()
end
end)
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
GameplayPaused
游戏暂停 属性表示玩家目前在启用 》 的地方处于暂停状态。它设置在客户端,但复制到服务器。要确定暂停状态,您可以使用此属性。
还见:
- Workspace.StreamingEnabled 用于控制是否启用内容传输,
- Workspace.StreamingIntegrityMode 和 Enum.StreamingIntegrityMode 对游戏暂停的更多细节。
HealthDisplayDistance
生命显示距离 Player 属性设置了这名玩家可以看到其他 Humanoid 生命条的距离以磅为单位。如果设置为 0,生命条不会显示。此属性默认设置为 StarterPlayer.HealthDisplayDistance。
如果人形的生命条可见,你可以使用 Humanoid.DisplayDistanceType 设置显示类型。
代码示例
This example demonstrates how to hide other Humanoid's (Player and NPC) health bars and names.
This is done by setting the player's Player.HealthDisplayDistance and Player.NameDisplayDistance properties to 0.
If you would like to display health bars and names, you set the properties to a value greater than 0. For instance, setting the properties to 100 means that the player will see other player's health and names up to 100 studs away.
To modify the default values for players, you can change the values of the StarterClass.Player.HealthDisplayDistance and StarterClass.Player.NameDisplayDistance properties.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0
LocaleId
本地Id Player 属性显示了本地玩家为他们的 Roblox 帐户设置的本地ID。它持有带有两个字母代码的字符串(例如,“en-us”)用于本地。
这可以用来确定游戏玩家群的地理人口结构,也是用于自动本地化体验内容的本地(见 GuiBase2d.AutoLocalize)。此属性允许从服务器访问玩家的本地。
还见 LocalizationService.RobloxLocaleId ,用于本地化内部内容的本地ID。当 Roblox 尚未内部支持本地玩家的设置本地时,这将是不同的值。
代码示例
This example demonstrates how to check the locale of a local player using the Player.LocaleId property. It prints a string with the two letter locale code for the locale of the local player.
For instance, if the player's local is within the US, the locale will be:
en-us
local Players = game:GetService("Players")
local player = Players.LocalPlayer
print(player.LocaleId)
MembershipType
此属性只能阅读以确定会员资格(不能设置为另一种会员输入)。它持有一个 Enum.MembershipType 枚列的帐户会员输入。
代码示例
The following example checks whether a player has Premium membership.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
if player.MembershipType == Enum.MembershipType.Premium then
-- Take some action specifically for Premium members
end
NameDisplayDistance
名称显示距离 StarterPlayer 属性设置了这名玩家在钉子距离上看到其他 Humanoid 名称的距离。如果属性设置为 0,名称将被隐藏。此属性默认设置为 StarterPlayer.NameDisplayDistance。
如果人形的生命条可见,你可以使用 Humanoid.DisplayDistanceType 设置显示类型。
代码示例
This example demonstrates how to hide other Humanoid's (Player and NPC) health bars and names.
This is done by setting the player's Player.HealthDisplayDistance and Player.NameDisplayDistance properties to 0.
If you would like to display health bars and names, you set the properties to a value greater than 0. For instance, setting the properties to 100 means that the player will see other player's health and names up to 100 studs away.
To modify the default values for players, you can change the values of the StarterClass.Player.HealthDisplayDistance and StarterClass.Player.NameDisplayDistance properties.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0
Neutral
中立属性决定玩家是否在特定团队上。
代码示例
This example checks if a player is neutral. If the player is neutral, the game prints:
Player is neutral!
If the player is not neutral, the game prints:
Player is not neutral!
Note: Although this example prints the value of the local player's neutral property, you can change the example to get the value for any player.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
if player.Neutral then
print("Player is neutral!")
else
print("Player is not neutral!")
end
PartyId
ReplicationFocus
复制焦点 Player 属性将部分聚焦在玩家周围进行复制。通过网络通信的不同 Roblox 系统(例如物理、传输等),根据对象距离复制焦点的程度进行复制,速率不同。
当此属性为 nil 时,它会恢复到默认行为,即将本地玩家的角色的 PrimaryPart 视为复制焦点。
此属性应仅在服务器上设置 Script,而不是 LocalScript。请注意,此属性不会更改或更新零件的网络所有权。
代码示例
This example creates a new BasePart and sets the Player's Player.ReplicationFocus to that part.
This demonstrates the functionality of the ReplicationFocus property. You can easily change the part that the focus is set to to change the replication focus.
local Players = game:GetService("Players")
local PLAYER_NAME = "polarpanda16"
local player = Players:WaitForChild(PLAYER_NAME)
local part = Instance.new("Part")
part.Parent = workspace
part.Name = "ReplicationFocusPart"
part.Anchored = true
player.ReplicationFocus = part
RespawnLocation
如果设置,玩家将在指定的 SpawnLocation 重生。此属性只能通过 Luau 设置,且必须包含指向有效的 SpawnLocation 的引用,该引用必须符合以下要求:
- 下辈子 Workspace
如果重生位置未设置为有效的 SpawnLocation ,那么默认生成逻辑将适用。了解有关此更多信息,请参阅SpawnLocation页面。
重生位置的替代品 Alternatives to RespawnLocation
- 使用 PVInstance:PivotTo() 实现自己的自定义生成逻辑,手动移动 Player.Character 。
代码示例
This code sample will set the player to always respawn from the last SpawnLocation they touched. New players will respawn from the SpawnLocation named 'FirstSpawn' until they touch a different SpawnLocation.
This is an alternative to using the AllowTeamChangeOnTouch property to switch SpawnLocations and does not require Teams.
local Players = game:GetService("Players")
local function addSpawn(spawnLocation)
-- listen for the spawn being touched
spawnLocation.Touched:Connect(function(hit)
local character = hit:FindFirstAncestorOfClass("Model")
if character then
local player = Players:GetPlayerFromCharacter(character)
if player and player.RespawnLocation ~= spawnLocation then
local humanoid = character:FindFirstChildOfClass("Humanoid")
-- make sure the character isn't dead
if humanoid and humanoid:GetState() ~= Enum.HumanoidStateType.Dead then
print("spawn set")
player.RespawnLocation = spawnLocation
end
end
end
end)
end
local firstSpawn
-- look through the workspace for spawns
for _, descendant in pairs(workspace:GetDescendants()) do
if descendant:IsA("SpawnLocation") then
if descendant.Name == "FirstSpawn" then
firstSpawn = descendant
end
addSpawn(descendant)
end
end
local function playerAdded(player)
player.RespawnLocation = firstSpawn
end
-- listen for new players
Players.PlayerAdded:Connect(playerAdded)
-- go through existing players
for _, player in pairs(Players:GetPlayers()) do
playerAdded(player)
end
StepIdOffset
Team
团队属性是指服务中的 对象的参考。它决定玩家所在的团队;如果 Player 不在团队上或有无效的 Player.TeamColor ,此属性是 nil 。当该属性设置时,玩家已加入 Team 和 Team.PlayerAdded 事件,并在相关的团队上触发。同样,Team.PlayerRemoved 在属性从某个 Team 中被取消时发生火焰。
代码示例
This code sample, although lengthy, is quite simple: detect when a player chats /play, then put them on the "Playing" team. When they die, move them back to the "Spectating" team.
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
local teamPlaying = Teams.Playing
local teamSpectators = Teams.Spectating
local playCommand = "/play"
local function play(player)
player.Team = teamPlaying
player.TeamColor = teamPlaying.TeamColor
-- Respawn the player (moves them to spawn location)
player:LoadCharacter()
end
local function onPlayerDied(player, _character)
-- When someone dies, put them on the spectator team
player.Team = teamSpectators
end
local function onPlayerSpawned(player, character)
local human = character:WaitForChild("Humanoid")
human.Died:Connect(function()
onPlayerDied(player, character)
end)
end
local function onPlayerChatted(player, message)
if message:sub(1, playCommand:len()):lower() == playCommand then
play(player)
end
end
local function onPlayerAdded(player)
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
player.Chatted:Connect(function(message, _recipient)
onPlayerChatted(player, message)
end)
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
This code sample allows any player to chat "/jointeam " where is the name of a team. It uses string manipulation using string.sub and string.lower to make the command case-insensitive and allow for partial matches. For example, "/jointeam red" will match the team "Red Robins".
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
-- Command to choose a team (note the trailing space)
local joinCommand = "/jointeam "
local function findTeamByName(name)
-- First, check for the exact name of a team
if Teams:FindFirstChild(name) then
return Teams[name]
end
-- Let's check for case-insensitive partial matches, like "red" for "Red Robins"
for _, team in pairs(Teams:GetChildren()) do
if team.Name:sub(1, name:len()):lower() == name:lower() then
return team
end
end
-- If we get to this point, no team matched the one we were looking for :(
end
local function onPlayerChatted(player, message, _recipient)
-- Note: string.sub(message, ...) is the same as message:sub(...)
if message:sub(1, joinCommand:len()):lower() == joinCommand:lower() then
-- Matched "/JOINTEAM xyz" to our join command prefix "/jointeam "
local teamName = message:sub(joinCommand:len() + 1) -- Cut out the "xyz" from "/jointeam xyz"
local team = findTeamByName(teamName)
if team then
-- Set the team!
player.Team = team
player.Neutral = false
else
-- Tell the player that team could not be found :(
player.Team = nil
player.Neutral = true
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
TeamColor
团队颜色属性决定玩家与哪个团队相关,根据该团队的 Team.TeamColor 。更改此属性将根据哪个团队拥有相同的 Player.Team 为他们的 BrickColor 来更改 Team.TeamColor。如果没有团队对象具有相关的团队颜色,玩家不会与团队匹配。
通常设置 Player.Team 为各自的 Team 而不使用此属性是更好的想法。设置此属性会导致在许多脚本中为特定团队重复相同的 BrickColor 值;这是你在遵守“不要重复自己”(DRY)原则时想要避免的情况。
代码示例
This code sample, although lengthy, is quite simple: detect when a player chats /play, then put them on the "Playing" team. When they die, move them back to the "Spectating" team.
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
local teamPlaying = Teams.Playing
local teamSpectators = Teams.Spectating
local playCommand = "/play"
local function play(player)
player.Team = teamPlaying
player.TeamColor = teamPlaying.TeamColor
-- Respawn the player (moves them to spawn location)
player:LoadCharacter()
end
local function onPlayerDied(player, _character)
-- When someone dies, put them on the spectator team
player.Team = teamSpectators
end
local function onPlayerSpawned(player, character)
local human = character:WaitForChild("Humanoid")
human.Died:Connect(function()
onPlayerDied(player, character)
end)
end
local function onPlayerChatted(player, message)
if message:sub(1, playCommand:len()):lower() == playCommand then
play(player)
end
end
local function onPlayerAdded(player)
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
player.Chatted:Connect(function(message, _recipient)
onPlayerChatted(player, message)
end)
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
ThirdPartyTextChatRestrictionStatus
UserId
用户ID是一个 属性,包含一个只读整数,用于在 Roblox 上唯一且一致地识别每个用户帐户。与玩家的 Instance.Name 不同,这个值永远不会根据用户当前的用户名更改为同一个帐户。
使用 GlobalDataStores 保存/加载玩家数据时,此属性是必不可少的。使用玩家的用户ID作为数据存储钥匙,使每个玩家都有独一无二的键。
代码示例
The below example would print the UserId of every user who entered a game.
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print(player.UserId)
end
Players.PlayerAdded:Connect(onPlayerAdded)
local Players = game:GetService("Players")
local player = Players:GetPlayerByUserId(1)
if player then
print("Player with userId 1 is in this server! Their name is: " .. player.Name)
else
print("Player with userId 1 is not in this server!")
end
The following code sample gives an example of a 'met the creator' badge system. This script will award a specified badge (BADGE_ID) to anyone who is in a server at the same time as the user associated with OWNER_ID.
local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
local OWNER_ID = 212423 -- can use game.CreatorId for published places
local BADGE_ID = 1
local ownerInGame = false
local function playerAdded(newPlayer)
if newPlayer.UserId == OWNER_ID then
-- if new player is the owner, set ownerInGame to true and give everyone the badge
ownerInGame = true
for _, player in pairs(Players:GetPlayers()) do
-- don't award the owner
if player ~= newPlayer then
BadgeService:AwardBadge(player.UserId, BADGE_ID)
end
end
elseif ownerInGame then
-- if the owner is in the game, award the badge
BadgeService:AwardBadge(newPlayer.UserId, BADGE_ID)
end
end
local function playerRemoving(oldPlayer)
if oldPlayer.UserId == OWNER_ID then
ownerInGame = false
end
end
Players.PlayerAdded:Connect(playerAdded)
Players.PlayerRemoving:Connect(playerRemoving)
This code sample retrieves a player's saved gold from a data store and puts the returned value onto the leaderboard. Note that this sample does not save players' gold — it only loads it.
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local goldDataStore = DataStoreService:GetDataStore("Gold")
local STARTING_GOLD = 100
local function onPlayerAdded(player)
local playerKey = "Player_" .. player.UserId
local leaderstats = Instance.new("IntValue")
leaderstats.Name = "leaderstats"
local gold = Instance.new("IntValue")
gold.Name = "Gold"
gold.Parent = leaderstats
local success, result = pcall(function()
return goldDataStore:GetAsync(playerKey) or STARTING_GOLD
end)
if success then
gold.Value = result
else
-- Failed to retrieve data
warn(result)
end
leaderstats.Parent = player
end
Players.PlayerAdded:Connect(onPlayerAdded)
方法
ClearCharacterAppearance
清除角色外观函数会从指定玩家的 Accessory , Shirt , Pants , CharacterMesh 和 BodyColors 中移除所有 Player.Character 。此外,它还移除玩家躯干上的 T 恤Decal。角色的身体部位颜色和面部将保持不变。如果玩家没有角色,此方法将无所作为。
它不会移除t-shirts、头部网格或面部。
返回
代码示例
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local function onChildRemoved(child)
print(child.ClassName, "removed from character")
end
character.ChildRemoved:Connect(onChildRemoved)
player:ClearCharacterAppearance()
--> BodyColors removed from character
--> ShirtGraphic removed from character
--> Shirt removed from character
--> Pants removed from character
--> CharacterMesh removed from character
--> Hat removed from character
--> Shirt removed from character
DistanceFromCharacter
距离从角色 Player 函数返回角色头和给定 Vector3 点之间的距离。如果玩家没有 Player.Character,它将返回 0。
这对于确定游戏中玩家与另一个对象或地点之间的距离有用。
如果您想确定两个非玩家实例或位置之间的距离,您可以使用以关注中/正在关注内容:
local distance = (position1 - position2).Magnitude
参数
从哪里测量玩家到的距离。
返回
玩家和位置之间的距离(钉子)。
代码示例
This example demonstrates how to measure the distance between a player's Player.Character and another location.
This code will print the distance of each player's character from the origin (0, 0, 0):
local Players = game:GetService("Players")
for _, player in pairs(Players:GetPlayers()) do
print(player:DistanceFromCharacter(Vector3.new(0, 0, 0)))
end
GetJoinData
返回包含描述玩家如何加入体验的信息的词典。词典包含以下任意字段:
<th>价值类型</th><th>描述</th></tr></thead><tbody><tr><th>源游戏ID</th><td>数字</td><td>从经验中传送过来的 Class.DataModel.GameId 的经验。仅在玩家传送到当前体验并且服务器调用传送函数时才会存在。</td></tr><tr><th>源地点ID</th><td>数字</td><td>从 玩家 传送到的地方的 Class.DataModel.PlaceId 。仅在玩家传送到当前位置并调用服务器的传送函数时才存在。</td></tr><tr><th>由玩家ID引用</th><td>数字</td><td>邀请当前玩家进入体验的玩家的 <code>Class.Player.UserId</code>。使用这些数据来识别推荐者并触发奖励逻辑。</td></tr><tr><th>成员</th><td>阵数组</td><td>包含 <code>Class.Player.UserId</code> 用户与 <code>玩家</code> 一起传送的用户数量的阵列。仅在玩家以群组的形式进行传送时才会出现。</td></tr><tr><th>传送数据</th><td>变体</td><td>反映原始传送中指定的 <code>teleportData</code> 。对于玩家传送到的服务器之间分享信息有用。仅在指定了 <code>teleportData</code> 并且服务器调用了传送函数时才存在。</td></tr><tr><th>发射数据</th><td>字符串</td><td>一个简单或 JSON 编码的字符串,包含指向 <a href="/production/promotion/deeplinks">深链接</a> URL 或 <code>Class.ExperienceInviteOptions.LaunchData</code> 的启动数据。</td></tr><tr><th>游戏加入上下文</th> <td>字典</td><td>包含游戏加入上下文相关信息的词典。它包含以下键:<ul>加入来源 : Enum.JoinSource 物品类型 : 可选 Enum.AvatarItemType 资产ID : 可选 字符串 服装ID : 可选 字符串 资产类型 : 可选 Enum.AssetType 加入类型 : 可选 string</ul></td></tr></tbody>
关键 |
---|
获取加入数据和传送数据
如果服务器启动了玩家的传送,返回该方法的词典包含玩家的传送数据。Player:GetJoinData() 方法只能用于服务器上的传送数据查询。要从客户端获取数据,请使用 TeleportService:GetLocalPlayerTeleportData() 。
与 TeleportService:GetLocalPlayerTeleportData() 不同,Player:GetJoinData() 仅提供满足以下安全要求的传送数据:
- 保证在过去 48 小时内由 Roblox 服务器发送。
- 保证使用此 Player 发送过。
- 保证 SourcePlaceId 和 SourceGameId 是数据发送到的地方和宇宙。这意味着您可以验证传送数据来自批准的场景。
由于这些数据由客户端传输,它仍然可能被滥用者滥用。玩家货币等敏感数据应通过安全解决方案传输,例如 内存存储。
返回
包含 PlaceId 和 UserId 值的词典(见描述中的表)。
代码示例
The following example tracks sources of traffic for analytics. By creating URLs with unique launch data for each social platform, you can determine the most popular traffic sources. The sample checks the source against a list of possible samples and discards any invalid sources because users can modify the launch data.
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local analyticsStore = DataStoreService:GetDataStore("Analytics")
local ALLOWED_SOURCES = {
"twitter",
"youtube",
"discord",
}
local function onPlayerAdded(player)
local source = player:GetJoinData().LaunchData
-- check if the provided source is valid
if source and table.find(ALLOWED_SOURCES, source) then
-- update the data store to track the source popularity
local success, result = pcall(analyticsStore.IncrementAsync, analyticsStore, source)
if success then
print(player.Name, "joined from", source, "- total:", result)
else
warn("Failed to record join source: " .. result)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
The following example generates a URL with the user's ID used as launch data. It then displays the URL in a read-only text box that makes it easy for the user to copy and share the link with their friends. When a user joins the game using a referral link, you can use the launch data to reward the referrer.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local DIRECT_JOIN_URL = "https://www.roblox.com/games/start?placeId=%d&launchData=%s"
local textBox = script.Parent
local function generateReferralURL(player)
return DIRECT_JOIN_URL:format(game.PlaceId, player.UserId)
end
local function highlightAll()
if -- avoid recursive property updates
textBox:IsFocused() and not (textBox.SelectionStart == 1 and textBox.CursorPosition == #textBox.Text + 1)
then
textBox.SelectionStart = 1
textBox.CursorPosition = #textBox.Text + 1
end
end
textBox.Focused:Connect(highlightAll)
textBox:GetPropertyChangedSignal("SelectionStart"):Connect(highlightAll)
textBox:GetPropertyChangedSignal("CursorPosition"):Connect(highlightAll)
textBox.TextEditable = false
textBox.ClearTextOnFocus = false
textBox.Text = generateReferralURL(player)
The following example is a function that converts a table into a string you can use as launch data. The provided data is JSON encoded, checked for valid character length, and escaped with percent signs.
local HttpService = game:GetService("HttpService")
local DATA_CHARACTER_LIMIT = 200
local function encodeTableAsLaunchData(data)
-- convert the table to a string
local jsonEncodedData = HttpService:JSONEncode(data)
if #jsonEncodedData <= DATA_CHARACTER_LIMIT then
-- escape potentially invalid characters, such as spaces
local urlEncodedData = HttpService:UrlEncode(jsonEncodedData)
return true, urlEncodedData
else
-- report character limit error
return false, ("Encoded table exceeds %d character limit"):format(DATA_CHARACTER_LIMIT)
end
end
local sampleData = {
joinMessage = "Hello!",
urlCreationDate = os.time(),
magicNumbers = {
534,
1337,
746733573,
},
}
local success, encodedData = encodeTableAsLaunchData(sampleData)
if success then
print(encodedData)
else
warn("failed to encode launch data: " .. encodedData)
end
The following example attempts to decode launch data, using pcall to prevent an error in case the data is corrupt.
local HttpService = game:GetService("HttpService")
local Players = game:GetService("Players")
local function onPlayerAdded(player)
local launchData = player:GetJoinData().LaunchData
if launchData then
-- attempt to decode the data
local success, result = pcall(HttpService.JSONDecode, HttpService, launchData)
if success then
print(player.Name, "joined with data:", result)
else
-- this is probably due to the user messing with the URL
warn("Failed to parse launch data:" .. result)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
The following code sample is an example of how teleport data can be retrieved on the server using Player:GetJoinData(). This code, when ran in a Script in ServerScriptService, will listen for new Player|Players joining the game. When they join it will retrieve their teleport data (verifying it came from a valid place) to find their current level.
local Players = game:GetService("Players")
local approvedPlaceIds = { 1 } -- insert approved PlaceIds here
local function isPlaceIdApproved(placeId)
for _, id in pairs(approvedPlaceIds) do
if id == placeId then
return true
end
end
return false
end
local function onPlayerAdded(player)
local joinData = player:GetJoinData()
-- verify this data was sent by an approved place
if isPlaceIdApproved(joinData.SourcePlaceId) then
local teleportData = joinData.TeleportData
if teleportData then
local currentLevel = teleportData.currentLevel
print(player.Name .. " is on level " .. currentLevel)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
GetMouse
获取鼠标 Player 函数返回客户端正在使用的 Mouse。玩家的鼠标实例可用于跟踪用户的鼠标输入,包括左右鼠标按钮点击和移动以及位置。
服务提供额外的功能和事件来跟踪用户输入 - 尤其是那些不使用鼠标的设备。
注意:
- 该项目 必须 在 LocalScript 中使用,以期望在线工作。
- 在 2014 年 7 月的更新后,鼠标的图标现在可以通过这种方法设置。
返回
代码示例
The below example will print:
Button 1 is down
whenever the Players.LocalPlayer left clicks.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local function onButton1Down()
print("Button 1 is down")
end
mouse.Button1Down:Connect(onButton1Down)
GetNetworkPing
获取网络延迟 返回 Player 在秒内的隔离网络延迟。“延迟”是数据从客户端发送到服务器,然后返回的时间测量。它不涉及数据解析或处理。
对于客户端 LocalScripts,此函数只能在 Players.LocalPlayer 上调用。这个函数对于识别和调试在高网络延迟场景中发生的问题有用。它也有用于抵消延迟,例如调整投射物的投掷动画速度。
返回
HasAppearanceLoaded
HasAppearanceLoadedPlayer函数返回玩家的Player.Character是否已加载的外观。
玩家的外观包括玩家的 Shirt , Pants 和 Accessories 等物品。
这对于确定玩家是否在加入游戏后加载了外观有用,可以使用 Players.PlayerAdded 事件进行跟踪。
返回
一个 boolean,表示玩家角色的外观是否已加载。
代码示例
This example prints the result of Player:HasAppearanceLoaded() after a player joins the game until the player's appearance has loaded.
local Players = game:GetService("Players")
local function onPlayerAdded(player)
local loaded = player:HasAppearanceLoaded()
print(loaded)
while not loaded do
loaded = player:HasAppearanceLoaded()
print(loaded)
task.wait()
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
IsVerified
返回一个 boolean 值,表示玩家的验证状态。当真实时,玩家被验证。验证包括,但不限于非 VoIP 电话号码或政府身份证验证。
当实施 IsVerified 时,请注意确保实施不会误封所有未验证的用户。
请注意,该方法只能在后端服务器上调用。调用它的客户端结果导致错误。此外,该方法始终会在 Studio 中返回 false 。
返回
一个指示玩家是否验证的 boolean 值。
代码示例
The following example prints "true" if the player is verified.
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print(player:IsVerified())
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Kick
Kick() 方法允许体验优雅地断开客户端并可选提供给断开的用户一条消息。这对于管理恶意用户有用。您只应允许信任的特定用户触发此方法对其他用户。
在 Player 上调用此方法无参数会使用户与服务器断开并提供默认通知消信息。在 Player 上调用此方法,并将一个字符串作为第一个参数替换默认消息使用提供的字符串。
当从 LocalScript 使用此方法时,只有本地用户的客户端可以被踢出。
参数
在踢出用户时显示的消息。
返回
Move
移动Player函数使玩家的角色在停止或被玩家中断控制之前走在指定的方向,直到停止或被玩家中断控制。
这对于在地图上移动的 NPC Humanoids - 但并不由实际玩家的输入控制。
请注意,函数的第二个参数表示提供的 Vector3 是否应将玩家相对于世界坐标移动(false)或玩家的 Camera(true).
参数
玩家应该移动工具的 Vector3 方向。
一个指示玩家是否相对于玩家的相镜头移动的 boolean 值。
返回
代码示例
Demonstrates moving a player relative to their camera's position using Player:Move().
The script first waits for the player's Character and Humanoid to load, as both are required before calling Player:Move(). Otherwise a warning will display in the Output.
local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
-- Wait for the player's character and humanoid, which must exist before calling :Move()
local character = localPlayer.Character or localPlayer.CharacterAdded:Wait()
character:WaitForChild("Humanoid")
-- The player will move until they are 50 studs away from the camera's position at the time of running
localPlayer:Move(Vector3.new(0, 0, -50), true)
SetAccountAge
SetAccountAge 函数设置玩家的 Player.AccountAge 天。
用于设置描述玩家帐户多久前注册的 Player 属性。
这不会设置帐户上玩家的年龄,但帐户自身相对于第一次创建时的年龄。
参数
帐户的年龄(天)。
返回
代码示例
This example demonstrates how the Player:SetAccountAge() function would be used if it was accessible. It sets the local player's account age to 100 days.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player:SetAccountAge(100)
This code sample adds a mark to players showing about how old their account is. The mark uses a player's account age to determine if they are a New Player, Veteran Player or Regular Player.
local Players = game:GetService("Players")
local MAX_AGE_NEW_PLAYER = 7 -- one week
local MIN_AGE_VETERAN = 365 -- one year
-- This function marks a part with text using a BillboardGui
local function mark(part, text)
local bbgui = Instance.new("BillboardGui")
bbgui.AlwaysOnTop = true
bbgui.StudsOffsetWorldSpace = Vector3.new(0, 2, 0)
bbgui.Size = UDim2.new(0, 200, 0, 50)
local textLabel = Instance.new("TextLabel")
textLabel.Size = UDim2.new(1, 0, 1, 0) -- Fill parent
textLabel.Text = text
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.BackgroundTransparency = 1
textLabel.Parent = bbgui
-- Add to part
bbgui.Parent = part
bbgui.Adornee = part
end
local function onPlayerSpawned(player, character)
local head = character:WaitForChild("Head")
if player.AccountAge >= MIN_AGE_VETERAN then
mark(head, "Veteran Player")
elseif player.AccountAge <= MAX_AGE_NEW_PLAYER then
mark(head, "New Player")
else
mark(head, "Regular Player")
end
end
local function onPlayerAdded(player)
-- Listen for this player spawning
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
SetSuperSafeChat
这个方法设置玩家是否看到通过 TextService:FilterStringAsync() 过滤的聊天,而不是通常的聊天。
local Players = game:GetService("Players")local player = Players.LocalPlayerplayer:SetSuperSafeChat(true)
无论玩家是否启用聊天过滤,所有聊天都应在播放给其他玩家或在玩家自己的屏幕上时被过滤TextService。TextService:FilterStringAsync() 返回一个可以根据消信息的预期使用情况进行不同过滤的 TextFilterResult 对象。
参数
一个 bool 指示玩家是否看到过滤的聊天。
返回
GetFriendsOnline
此函数返回一个在线朋友的字典阵列,由 maxFriends 值限制。该函数使用 30 秒缓存。
在返回的数组中,一些字段仅存在于特定的位置类型。例如, PlaceId 将不会在 LocationType 为0(移动网站)时出现。
<th>类型</th><th>描述</th></tr></thead><tbody><tr><td><b>访客ID</b></td><td>数字</td><td>朋好友的 <code>Class.Player.UserId</code>。</td></tr><tr><td><b>用户名</b></td><td>字符串</td><td>朋好友的用户名。</td></tr><tr><td><b>显示名称</b></td><td>字符串</td><td>朋好友的 <code>Class.Player.DisplayName</code>。</td></tr><tr><td><b>最后在线</b></td><td>字符串</td><td>当朋友最后在线时。</td></tr><tr><td><b>是否在线</b></td><td>boolean 类型</td><td>如果朋友当前在线。</td></tr><tr><td><b>最后位置</b></td><td>字符串</td><td>朋好友当前位置的名称。</td></tr><tr><td><b>地点ID</b></td><td>数字</td><td>朋好友最后位置的地点ID。</td></tr><tr><td><b>游戏ID</b></td><td>字符串</td><td>朋好友最后位置的 <code>数据模型/工作ID</code>。</td></tr><tr><td><b>位置类型</b></td> <td>数量</td><td>朋好友最后的位置类型: 0 移动网站 移动游戏网站 2 网页 3 桌面应用程序 桌面应用程序 移动应用程序 桌面应用程序 移动应用程序 移动应用程序 桌面应用程序 移动应用程序 移动应用程序 移动应用程序 移动应用程序 移动应用程序 移动应用程序 移动应用程序 移动应用程序 移动应用程序 移动应用程序 移动应用程序 移动应用程序 移动应plications 移动应用程序 移动应plications 移动应plications 移动应plications 移动应plications 移动应plications 移动应plications 移动应plications 移动应plications 移动应plications 移动应plications 移动应plications 移动应plications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移able applications 移动 applications 移able applications 移able applications 移动 applications 移able applications 移动 applications 移able applications 移able applications 移动 applications 移动 applications 移动 applications 移able applications 移able applications 移动 applications 移动 applications 移动 applications 移动 applications 移able applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动 applications 移动应用 移动 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应plications 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用程 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用 移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动应用移动移动应用移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动移动</td></tr></tbody>
名称 |
---|
参数
要回传的在线好友最大数量。
返回
在线朋友的词典(见上表)。
代码示例
This example demonstrates how to get a dictionary of a player's online friends. It returns the maximum number of friends specified by the argument, or 200 if an argument is not provided.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local success, result = pcall(player.GetFriendsOnline, player, 10)
if success then
for _, friend in pairs(result) do
print(friend.UserName)
end
else
warn("Failed to get online players: " .. result)
end
GetRankInGroup
GetRankInGroup Player 函数返回玩家在群组中的排名作为一个整数,在 0 和 255 之间,其中 0 是非成员,255 是群组的所有者。
使用此在 Script 中,与 LocalScript 相比,将无法获得最新信息。如果玩家在游戏期间离开群组,GetRankInGroup仍然认为他们属于该群组,直到他们离开。但是,当使用 LocalScript 时,这不会发生。
这是因为方法缓存结果,因此多次调用同一玩家上同一组ID的 GetRankInGroup 将产生与方法首次调用时给定的组ID相同的结果。缓存行为是基于每个伙伴的:服务器不会与客户端共享相同的缓存。
参数
指定群组的 groupId。
返回
玩家在群组中的排名。
代码示例
The code below will check if a player that has entered the game has a rank equal to 255, in a group with an ID of 2. If they are, it will print "Player is the owner of the group, 'LOL'!", otherwise "Player is NOT the owner of the group, 'LOL'!" will be printed to the output.
local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:GetRankInGroup(2) == 255 then
print("Player is the owner of the group, 'LOL'!")
else
print("Player is NOT the owner of the group, 'LOL'!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
GetRoleInGroup
GetRoleInGroup Player 函数返回玩家在群组中的角色为字符串,或 访客 如果玩家不是群组的一部分。
使用此在 Script 中,与 LocalScript 相比,将无法获得最新信息。如果玩家在游戏期间离开群组,GetRoleInGroup仍然认为他们属于该群组,直到他们离开。但是,当使用 LocalScript 时,这不会发生。
这是因为方法缓存结果,因此多次调用同一个玩家上同一个组ID的 GetRoleInGroup 将产生与方法首次调用时给出的组ID相同的结果。缓存行为是基于每个伙伴的:服务器不会与客户端共享相同的缓存。
参数
指定群组的 groupId。
返回
玩家在指定的群组中的角色,或 访客 如果玩家不是成会员 / 成员。
代码示例
The code below will print the name of the rank that the player is currently a part of, in a specific group. In this instance we're checking what rank the player is within a group which has a group ID of 2.
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print("Player is ranked as '", player:GetRoleInGroup(2), "' in group, 'LOL'!")
end
Players.PlayerAdded:Connect(onPlayerAdded)
IsFriendsWith
这个函数向 Roblox 网站发送请求,询问玩家是否是另一名用户的朋友,根据该用户的 Player.UserId 来决定。此函数会将结果缓存,因此多次调用函数在同一个玩家上与相同 Player.UserId 的多个调用可能不会产生最新的结果。在 LocalScript 中使用时不会发生这种情况。
参数
指定玩家的 Player.UserId 。
返回
一个 bool 指示玩家是否是指定用户的朋友。
代码示例
The below example would print whether or not a recently added player is friends with Gordonrox24.
local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:IsFriendsWith(146569) then
print(player.Name .. " is friends with gordonrox24!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
IsInGroup
IsInGroup Player 函数向 Roblox 网站发送请求,询问玩家是否是该群组的成员,给出该群组的 ID。
使用此在 Script 中,与 LocalScript 相比,将无法获得最新信息。如果玩家在游戏期间离开群组,IsInGroup仍然会认为他们属于该群组,直到他们离开。但是,当使用 LocalScript 时,这不会发生。
这是因为方法缓存结果,因此多次调用与同一组ID的同一玩家上的 IsInGroup 方法将产生与方法首次调用时给定的组ID相同的结果。缓存行为是基于每个伙伴的:服务器不会与客户端共享相同的缓存。
参数
指定群组的 groupId。
返回
一个 bool 指示玩家是否属于指定的群组。
代码示例
The below example will print "Player is in the Roblox Fan club!" if the newly added player is in the group with a groupId of 7.
local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:IsInGroup(7) then
print("Player is in the Roblox Fan club!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
LoadCharacter
加载角色 Player 函数创建一个新角色给玩家,移除旧角色。它还清除玩家的 Backpack 和 PlayerGui .
这在您想要在不杀死玩家的情况下重新加载角色时有用,例如当您想要在更改玩家 Player.CharacterAppearance 后加载新角色外观时。
注意:函数与 Player:LoadCharacterBlocking() 相似,但请求以异步方式处理,而不是同步方式。这意味着其他任务可以在角色加载时继续进行,包括游戏渲染和任何其他任务。此外,此函数可以在脚本中使用,而 LoadCharacterBlocking 不能。
在为个人玩家调用 LoadCharacter 之后,不建议在该玩家的 Player.CharacterAppearanceLoaded 事件发生后再次调用它,直到该玩家的事件触发。
角色加载事件顺序
调用 R15 虚拟形象与 Player:LoadCharacter() 会触发以下顺序的事件(注意:R6 排序不同):
- 玩家.角色集
- 玩家.角色添加火焰
- 玩家.改变发生了带有“角色”值的火焰
- 角色外观初始化
- 玩家.角色外观已加载火
- 角色.父设置为数据模型
- 角色模型和角色缩放
- 角色移动到生成地点
- 加载角色返回
返回
代码示例
This script turns off auto-loading and simulates character respawning.
local Players = game:GetService("Players")
local RESPAWN_DELAY = 5
Players.CharacterAutoLoads = false
local function onPlayerAdded(player)
local function onCharacterAdded(character)
local humanoid = character:WaitForChild("Humanoid")
local function onDied()
task.wait(RESPAWN_DELAY)
player:LoadCharacter()
end
humanoid.Died:Connect(onDied)
end
player.CharacterAdded:Connect(onCharacterAdded)
player:LoadCharacter()
end
Players.PlayerAdded:Connect(onPlayerAdded)
LoadCharacterWithHumanoidDescription
这个函数生成一个虚拟形象,所以它具备了传递到 HumanoidDescription 中的所有装备。
在为个人玩家调用 LoadCharacterWithHumanoidDescription 之后,不建议在该玩家的 Player.CharacterAppearanceLoaded 事件触发后再次调用该函数,直到该玩家的事件触发。
还见:
- 人形描述系统 , 一篇文章,更详细地解释了人形描述系统,并提供了几个脚本示例
参数
包含身体部位/颜色、身体缩放、配件、服装和动画等特性的 HumanoidDescription 文件,将装备到加载的角色。
返回
代码示例
To create a HumanoidDescription and then spawn a character with that description applied, add a Script (not a LocalScript) to the workspace and add this code to it.
local Players = game:GetService("Players")
Players.CharacterAutoLoads = false
local function onPlayerAdded(player)
local humanoidDescription = Instance.new("HumanoidDescription")
humanoidDescription.HatAccessory = "2551510151,2535600138"
humanoidDescription.BodyTypeScale = 0.1
humanoidDescription.ClimbAnimation = 619521311
humanoidDescription.Face = 86487700
humanoidDescription.GraphicTShirt = 1711661
humanoidDescription.HeadColor = Color3.new(0, 1, 0)
player:LoadCharacterWithHumanoidDescription(humanoidDescription)
end
Players.PlayerAdded:Connect(onPlayerAdded)
RequestStreamAroundAsync
对于启用了实例 直播 的体验,请求服务器向指定的 X 、 Y 、 Z 位置在 3D 世界流向玩家区域(部分和地形)。如果体验知道玩家的 CFrame 将在不久的将来设置为指定位置,那么它会很有用。没有通过这个调用提供位置,玩家可能没有为目的地传输内容,导致传输暂停或其他不可接受的行为。
该调用的效果将是暂时的,没有保证在指定位置附近会流传的内容。客户端内存限制和网络条件可能会影响客户端上可用的内容。
使用注意
要求在区域周围进行流式传输不是 保证 内容在请求完成时会存在,因为流式传输受到客户端网络带宽、内存限制等因素的影响。
参数
需要直播的世界位置。
对请求的可选时间限制,引擎在放弃请求之前尝试传播区域参数 position 的最大持续时间。如果您未指定值,超时效果几乎无限。然而,如果客户端内存不足,引擎放弃所有的串流请求,即使它们仍然在时间限制内。
返回
活动
CharacterAdded
当玩家的角色生成(或重生)时, 角色添加 事件发生。此事件很快发生后设置 Player.Character 为非 nil 值或调用 Player:LoadCharacter(),这是在角色被父辈到 Workspace 之前。
这可以与 Player.CharacterRemoving 事件一起使用,该事件在玩家角色即将被移除之前发射,通常在死亡后。因此,这两个事件都可能在玩家死亡然后重生到一个场景时触发多次。如果您想检测玩家何时加入或离开游戏,请使用 Players.PlayerAdded 和 Players.PlayerRemoving 事件。
请注意,当此事件触发时,Humanoid和其默认身体部位(头、躯干和肢体)会存在,但像Hats、Shirts和Pants这样的服装项目可能需要几秒钟才能添加到角色。连接Instance.ChildAdded在添加的角色上检测这些,或等待Player.CharacterAppearanceLoaded事件确保角色已装备所有设备。
参数
生成/重生的角色实例。
代码示例
This code sample demonstrates the usage of Players.PlayerAdded, Player.CharacterAdded and Player.CharacterRemoving in order to detect the spawning and despawning of players' characters. You can use this as a boilerplate script to make changes to players' characters as they spawn, such as changing Humanoid.WalkSpeed.
local Players = game:GetService("Players")
local function onCharacterAdded(character)
print(character.Name .. " has spawned")
end
local function onCharacterRemoving(character)
print(character.Name .. " is despawning")
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
player.CharacterRemoving:Connect(onCharacterRemoving)
end
Players.PlayerAdded:Connect(onPlayerAdded)
This code sample will cause players to respawn at the same place they died. It does this by keeping track of where the player despawned using Player.CharacterRemoving. Note that the player's location is saved on-despawn, not on-death. This can be problematic if the player falls off a ledge and dies due to Workspace.FallenPartsDestroyHeight - their respawn position won't be saved in this case.
It's also important to note the need to "forget" the location of players who leave the game. We use Instance.ChildRemoved on Players instead of Players.PlayerRemoving. This is because PlayerRemoving fires before CharacterRemoving - and we need to make sure we don't forget the player's respawn location then immediately remember a new one (this is a memory leak; potentially many players could visit, respawn and leave). So, we use ChildRemoved on Players so the event fires after the character is removed.
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
-- This table maps "Player" objects to Vector3
local respawnLocations = {}
local function onCharacterAdded(character)
local player = Players:GetPlayerFromCharacter(character)
-- Check if we saved a respawn location for this player
if respawnLocations[player] then
-- Teleport the player there when their HumanoidRootPart is available
local hrp = character:WaitForChild("HumanoidRootPart")
-- Wait a brief moment before teleporting, as Roblox will teleport the
-- player to their designated SpawnLocation (which we will override)
RunService.Stepped:wait()
hrp.CFrame = CFrame.new(respawnLocations[player] + Vector3.new(0, 3.5, 0))
end
end
local function onCharacterRemoving(character)
-- Get the player and their HumanoidRootPart and save their death location
local player = Players:GetPlayerFromCharacter(character)
local hrp = character:FindFirstChild("HumanoidRootPart")
if hrp then
respawnLocations[player] = hrp.Position
end
end
local function onPlayerAdded(player)
-- Listen for spawns/despawns
player.CharacterAdded:Connect(onCharacterAdded)
player.CharacterRemoving:Connect(onCharacterRemoving)
end
local function onPlayerRemoved(player)
-- Forget the respawn location of any player who is leaving; this prevents
-- a memory leak if potentially many players visit
respawnLocations[player] = nil
end
-- Note that we're NOT using PlayerRemoving here, since CharacterRemoving fires
-- AFTER PlayerRemoving, we don't want to forget the respawn location then instantly
-- save another right after
Players.PlayerAdded:Connect(onPlayerAdded)
Players.ChildRemoved:Connect(onPlayerRemoved)
This code sample automatically removes Accessory objects like hats from the Player's character when they respawn. Warning: this includes hair, so this script may cause acute baldness.
When the Character() is added, we wait for RunService.Stepped to fire once (using the wait function of events). This is so the accessory removal logic runs one frame after the character spawns. A warning can appear if you delete accessories too quickly after the player spawns, so waiting one frame will avoid that.
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local function destroyAccessory(object)
if object:IsA("Hat") or object:IsA("Accessory") then
object:Destroy()
end
end
local function onCharacterAdded(character)
-- Wait a brief moment before removing accessories to avoid the
-- "Something unexpectedly set ___ parent to NULL" warning
RunService.Stepped:Wait()
-- Check for any existing accessories in the player's character
for _, child in pairs(character:GetChildren()) do
destroyAccessory(child)
end
-- Hats may be added to the character a moment after
-- CharacterAdded fires, so we listen for those using ChildAdded
character.ChildAdded:Connect(destroyAccessory)
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)
CharacterAppearanceLoaded
当全部外观的 Player.Character 被插入时,此事件发生。
A Player.Character 一般有一系列对其外观进行修改的对象,包括 Accoutrements , Shirts , Pants 和 CharacterMeshes .当所有这些对象都插入到 Player.Character 中时,该事件将发射。
该事件仅在服务器上发生。
这个事件的一个使用是确保所有配件在摧毁它们之前都已加载。请参阅下面的示例。
参数
The Player.Character Model .
代码示例
This code sample will wait for accessories to fully load, print out how many there are, and then destroy them all.
local Players = game:GetService("Players")
local function onPlayerAddedAsync(player)
local connection = player.CharacterAppearanceLoaded:Connect(function(character)
-- All accessories have loaded at this point
local humanoid = character:FindFirstChildOfClass("Humanoid")
local numAccessories = #humanoid:GetAccessories()
print(("Destroying %d accessories for %s"):format(numAccessories, player.Name))
humanoid:RemoveAccessories()
end)
-- Make sure we disconnect our connection to the player after they leave
-- to allow the player to get garbage collected
player.AncestryChanged:Wait()
connection:Disconnect()
end
for _, player in Players:GetPlayers() do
task.spawn(onPlayerAddedAsync, player)
end
Players.PlayerAdded:Connect(onPlayerAddedAsync)
CharacterRemoving
角色移除事件在玩家的角色被移除之前发生,例如当玩家重生时。
此事件可以与 Player.CharacterAdded 事件一起使用,当玩家角色生成或重生时触发。例实例,如果你想每次玩家生成和死亡时打印一条消息:
local Players = game:GetService("Players")
local function onCharacterSpawned(player)
print(player.Name .. " is spawning")
end
local function onCharacterDespawned(player)
print(player.Name .. " is despawning")
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(function()
onCharacterSpawned(player)
end)
player.CharacterRemoving:Connect(function()
onCharacterDespawned(player)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
该事件仅关注 Character 的 Player 。如果你需要追踪玩家何时加入/离开游戏,使用事件 Players.PlayerAdded 和 Players.PlayerRemoving 。
参数
正在删除的角色实例。
代码示例
This example prints the name of the character being removed, followed by "has died".
For instance, if Shedletsky's character was to die in-game, "Shedletsky has died." would be printed.
game.Players.PlayerAdded:Connect(function(player)
player.CharacterRemoving:Connect(function(character)
print(character.Name .. " has died.")
end)
end)
Chatted
聊天事件发生当 Player 键入消息并按下 Roblox 提供的聊天栏的 Enter 键时。这是由默认聊天脚本使用一些 Luau 绑定来实现的。您可以使用 StarterGui:SetCoreGuiEnabled() 防止玩家聊天,并禁用聊天 Enum.CoreGuiType。
聊天命令
使用此事件和一些字符串操作函数,例如 string.sub() 和 string.lower() , 可以创建聊天命令,甚至使用玩家名称作为参数。通常,命令以前缀如 heal PlayerName 开头。要检查字符串中的前缀,请在消息上使用 string.sub() 来检查消信息的子串:string.sub(message, 1, 6) == "/heal " (注意包含空空间)。然后,再次使用 string.sub() 来提取命令的剩余部分:string.sub(message, 7) 将等于玩家名称。检查该玩家是否存在,如果存在,执行命令的行动(在这个例子中,治疗他们)。检查代码示例以获取聊天命令的示例。
过滤
使用此事件发射的消息文本是 未过滤 。如果您以任何形式向其他玩家显示聊天输入,必须使用 Chat:FilterStringAsync() 进行过滤。创建自己的聊天系统时,请记住这一点;如果你的游戏未能正确过滤聊天,它可能会受到审核行动的影响。
参数
代码示例
Setting chatted for all players. There is an easy way to make the Chatted event registered on all players. Simply use the Players.PlayerAdded event in combination with this event.
local Players = game:GetService("Players")
local function onPlayerAdded(player)
local function onChatted(message)
-- do stuff with message and player
print(message)
end
player.Chatted:Connect(onChatted)
end
Players.PlayerAdded:Connect(onPlayerAdded)
This code sample, although lengthy, is quite simple: detect when a player chats /play, then put them on the "Playing" team. When they die, move them back to the "Spectating" team.
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
local teamPlaying = Teams.Playing
local teamSpectators = Teams.Spectating
local playCommand = "/play"
local function play(player)
player.Team = teamPlaying
player.TeamColor = teamPlaying.TeamColor
-- Respawn the player (moves them to spawn location)
player:LoadCharacter()
end
local function onPlayerDied(player, _character)
-- When someone dies, put them on the spectator team
player.Team = teamSpectators
end
local function onPlayerSpawned(player, character)
local human = character:WaitForChild("Humanoid")
human.Died:Connect(function()
onPlayerDied(player, character)
end)
end
local function onPlayerChatted(player, message)
if message:sub(1, playCommand:len()):lower() == playCommand then
play(player)
end
end
local function onPlayerAdded(player)
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
player.Chatted:Connect(function(message, _recipient)
onPlayerChatted(player, message)
end)
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
This code sample allows any player to chat "/jointeam " where is the name of a team. It uses string manipulation using string.sub and string.lower to make the command case-insensitive and allow for partial matches. For example, "/jointeam red" will match the team "Red Robins".
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
-- Command to choose a team (note the trailing space)
local joinCommand = "/jointeam "
local function findTeamByName(name)
-- First, check for the exact name of a team
if Teams:FindFirstChild(name) then
return Teams[name]
end
-- Let's check for case-insensitive partial matches, like "red" for "Red Robins"
for _, team in pairs(Teams:GetChildren()) do
if team.Name:sub(1, name:len()):lower() == name:lower() then
return team
end
end
-- If we get to this point, no team matched the one we were looking for :(
end
local function onPlayerChatted(player, message, _recipient)
-- Note: string.sub(message, ...) is the same as message:sub(...)
if message:sub(1, joinCommand:len()):lower() == joinCommand:lower() then
-- Matched "/JOINTEAM xyz" to our join command prefix "/jointeam "
local teamName = message:sub(joinCommand:len() + 1) -- Cut out the "xyz" from "/jointeam xyz"
local team = findTeamByName(teamName)
if team then
-- Set the team!
player.Team = team
player.Neutral = false
else
-- Tell the player that team could not be found :(
player.Team = nil
player.Neutral = true
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Idled
此事件发生大约两分钟后,游戏引擎将 player 分类为空闲。时间是自那一刻起已过的秒数。事件继续每隔 30 秒发射,直到玩家闲置为止。
此事件仅在客户端脚本中发生,不在服务器脚本中;使用 RemoteEvent 通知服务器空闲玩家。
Roblox 会自动断开至少 20 分钟闲置的玩家,因此此事件对警告玩家他们即将被断开有用,在那 20 分钟之前断开玩家或其他远离键盘(AFK)功能。
要跟踪自动断开发生的频率,请尝试将此事件与 Players.PlayerRemoving 发生的情况相关。
参数
玩家闲置的时间(秒)。
代码示例
Prints how long a player has been idle for.
local Players = game:GetService("Players")
local function onIdled(idleTime)
print(`Player has been idle for {idleTime} seconds`)
if idleTime > 900 then
-- warn player that they've been idle for 15 minutes
-- and will be disconnected in another 5
end
end
Players.LocalPlayer.Idled:Connect(onIdled)
OnTeleport
当玩家的传送状态发生变化时发射。该事件对于检测是否成功传送具有用处。
传送状态是什么?
当使用 TeleportService 传送请求时,传送到 Player 之前有一系列阶段。当前阶段由 OnTeleport 提供的 Enum.TeleportState 值表示。请参阅下面的实用示例。
参数
新的 Enum.TeleportState 的 Player .
如果使用了 TeleportService:TeleportToSpawnByName() 传送到的名称,将传送到的名称。
代码示例
This example prints which stage of a teleport a player is at, as well as printing if the teleport was a failure.
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local playerOnTeleport = player
player.OnTeleport:Connect(function(teleportState, _placeId, _spawnName)
if teleportState == Enum.TeleportState.Started then
print("Teleport started (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.WaitingForServer then
print("Teleport waiting for server (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.InProgress then
print("Teleport in progress (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.Failed then
print("Teleport failed! (" .. playerOnTeleport.Name .. ")")
end
end)
end)