Player

显示已弃用

*此内容使用人工智能(Beta)翻译,可能包含错误。若要查看英文页面,请点按 此处

一个 Player 对象是一个当前连接的客户端。这些对象在新玩家连接时添加到 Players 服务,然后在最终从服务器解除连接时移除。

Class.Instance.Name 属性反映玩家的用户名。 保存有关玩家的信息时,您应该使用其 Player.UserId ,因为玩家可能会更改他们的用户名。

Players 服务中,您可以使用几种类似的方法来与玩家对象工作。使用它们的相应 Instance 方法:

代码示例

Leaderstats

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)

概要

属性

方法

活动

属性

AccountAge

只读
未复制
读取并联

AccountAge 是一个 Player 属性,描述玩家的帐户在几天内注册。它使用 Player:SetAccountAge() 函数设置,无法通过脚本访问。

此属性有助于在特定情况下显示新 Roblox 玩家的内容,例如教程。

代码示例

Account Age Mark

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

读取并联

启用自动跳转 属性决定 Player.Character 使用移动设备时是否会在碰到障碍时自动跳转。 这可以在移动设备上导航更多级别。

当玩家加入游戏时, StarterPlayer.AutoJumpEnabled 值确定这个属性的初始状态。然后,这个属性确定 Humanoid.AutoJumpEnabled 属性的 Player.Character 在生重生点时的自动跳跃行为。 在其他 words, 是可能

代码示例

Auto-Jump Toggle

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 属性设置在 Camera 可以从角色中使用的最大距离。

它以其他的话就是控制玩家的相机允许缩小的最大距离。

这个属性的默认值是 StarterPlayer.CameraMaxZoomDistance 。如果这个值设置为小于 Player.CameraMinZoomDistance ,它将被提升至 CameraMinZoomDistance。

代码示例

Setting Camera Zoom Distance

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75

CameraMinZoomDistance

读取并联

CameraMinZoonDistance Player 属性设置在 Camera 可以从角色中使用的默认摄像头的最小距离。

它的另一个名字是“最小距离”,它允许玩家的相机放大的最小距离。

这个属性的默认值是 StarterPlayer.CameraMinZoomDistance 。如果这个值设置为高于 Player.CameraMaxZoomDistance 的任何值,它将被减少至 CameraMaxZoomDistance。

代码示例

Setting Camera Zoom Distance

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75

CameraMode

读取并联

CameraMode 属性设置玩家的相机模式,默认为第三人称。

第三人称

在默认第三人称模式(Enum.CameraMode.Classic )中,角色可以在相镜头中查看。在此模式中,默认行为是:

  • 玩家可以右击并拖动(鼠标)、点击并拖动(移动)、使用副手柄(游戏手柄)或按左/右箭头(键盘)来旋转相机在他们的角色。
  • 当玩家移动他们的角色时,它们面向相应的移动方向。
  • 玩家可以放大和缩小,甚至可以在全面放大到第一人称。

第一人称

在第一人称模式 (Enum.CameraMode.LockFirstPerson) 的情况下,玩家的相机会在整个方向上缩放。除非有一个可见的 GUI 现象,其他 GUI 属性设置为 GuiButton.Modal ,移动鼠标、触摸拖动在移动设备上或使用游戏手柄上的副键盘来旋转相机。

代码示例

Playing in First Person

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMode = Enum.CameraMode.LockFirstPerson

CanLoadCharacterAppearance

读取并联

CanLoadCharacterAppearance Player 属性决定角色的外观在玩家生成时是否会被加载。默认值为 StarterPlayer.LoadPlayerAppearance

如果 true,角色会加载与玩家的 Player.CharacterAppearanceId 相对应的玩家外观。

如果 ,玩家将以默认外观生成 - 灰色角色模型 without any 帽子,衬衫,裤子等。

尝试在角色生成后设置属性不会更改角色,您必须调用 Player:LoadCharacter() 来加载新的外观。

代码示例

Disabling a Player's Appearance

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CanLoadCharacterAppearance = false

Character

读取并联

Character 属性包含一个引用于模拟玩家在体验中使用虚拟形象的身体部位、脚本和其他对象的对象。模型是由 Model 父级,但它可以

最初,此属性是 nil ,并且在玩家的角色首次生成时设置。使用 Player.CharacterAdded 事件来检测玩家角色正常加载时间,并使用 Player.CharacterRemoving 事件来检测角色即将 despawn 。避免使用 1> Class.Object:GetPropertyChanged

注意,LocalScriptsStarterGuiStarterPack 到玩家的 2>Class.


local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character
if not character or character.Parent == nil then
character = player.CharacterAdded:Wait()
end

CharacterAppearanceId

读取并联

此属性确定玩家的角色外观用于玩家的 Player.Character 。默认情况下,此属性是 Player.UserId ,它使用玩家在 Roblox 网站上创建的头像来创建玩家的角色外观。

将此属性更改为其他帐户的用户ID 会导致玩家以该帐户的外观(帽子、上衣、裤子等)重生。

游戏还可以通过修改 StarterPlayer.LoadCharacterAppearance 属性来切换是否要加载玩家的角色。

代码示例

Disguise Command

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 属性确定玩家使用带有鼠标和键盘的设备时,玩家移动相机的方式。 见 Enum.DevComputerCameraMovementMode 了解所有可用的相机控制模式的描述。 此属性无法使用 LocalScript (它必须在服务器上使用 Script )。

此属性的默认值由 StarterPlayer.DevComputerCameraMovementMode 决定。

在此属性名称中的“电脑”指向不是 TouchEnabled ,不是 GamepadEnabled 设备。

设置为 UserChoice 时,玩家可以在 Roblox 游戏设置中选择任何控制模式(包括 脚本 )。一通用来说,允许玩家选择其控制模式以最大限度地提高可用性。

通过将此属性设置为 脚本 来创建自定义控制程序。

此属性不会影响使用触摸设备的玩家。请参阅Player.DevTouchCameraMode

代码示例

Setting a Player's Camera Movement Mode (Desktop)

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设备。

设置为 User Choice 时,玩家可以在 Roblox 游戏设置中选择任何控制模式(包括 脚本 )。一通用来说,允许玩家选择其控制模式以最大限度地提高可用性。

通过将此属性设置为 脚本 来创建自定义控制程序。

此属性不会影响使用触摸设备的玩家。请参阅Player.DevTouchMovementMode

代码示例

Setting a Player's Movement Mode (Desktop)

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 来切换 Class.Mouse 锁。玩家可以在 Roblox 游戏设置中禁用鼠标锁定开关。默认情况下,此属性设置为 StarterPlayer.EnableMouseLockOption 值。这可以在服务器端在运行时使用 <

当鼠标锁定时,玩家的鼠标处于屏幕中心。移动鼠标会将相机环绕玩家的 character ,角色将朝着玩家的角色 camera 的方向面向相同。它还会在玩家角色的右肩上偏移相机视图。

注意,Shift-lock 相关 API 正在被弃用,因此您建议使用 UserInputService.MouseBehavior 而不是使用它来锁定鼠标。

代码示例

Toggling Mouse Lock Ability

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 属性确定玩家使用 TouchEnabled 设备时,玩家的相机移动方式。见 Enum.DevTouchCameraMovementMode 了解每个可用的相机控制模式的描述。此属性无法通过使用 LocalScript (它必须在服务器上使用

此属性的默认值由 StarterPlayer.DevTouchCameraMovementMode 决定。

设置为 User Choice 时,玩家可以在 Roblox 游戏设置中选择任何控制模式(包括 脚本 )。一通用来说,允许玩家选择其控制模式以最大限度地提高可用性。

通过将此属性设置为 脚本 来创建自定义控制程序。

此属性不会影响使用触摸设备的玩家。请参阅 Player.DevComputerCameraMovementMode

代码示例

Setting a Player's Camera Movement Mode (Touch)

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 (它必须在服务器上使用 2> Class

该属性的默认值由 StarterPlayer.DevTouchMovementMode 决定。

设置为 UserChoice 时,玩家可以在 Roblox 游戏设置中选择任何控制模式(包括 脚本 )。一通用来说,允许玩家选择其控制模式以最大限度地提高可用性。

通过将此属性设置为 脚本 来创建自定义控制程序。

此属性不会影响使用触摸设备的玩家。请参阅 Player.DevComputerMovementMode

代码示例

Setting a Player's Movement Mode (Touch)

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

读取并联

DisplayName 是一个 Player 属性,该属性包含与 Player 对象关联的认证用户的显示名称。与用户名不同,显示名称是玩家向其他人显示的非独特名称。如果 Roblox 用户未选择一个,该属性将以 1>Name1> 属性的相同方式读取。

注意:

  • 由于显示名称不是唯一的,因此在单个实例中的两个玩家可能有相同的名称。如果您需要一个全球独一无二的识别器,例如玩家,请使用 Player.UserId (静态) 或 Player.Name (当前用户名) 。
  • 使用 Player.LoadCharacter 或 Roblox 引擎生成的角色将有其 Humanoid.DisplayName 属性分配到 Player.DisplayName 属性。
  • 显示名称可能包含不符号字符在字符串中。请参阅 UTF-8 获取有关使用符号字符串的更多信息。

FollowUserId

只读
未复制
读取并联

Class.Player 属性,该属性包含玩家跟随到游戏的用户的 Player.UserId 。如果玩家没有跟随任何人进入游戏,该属性将为 0。这个属性对于警告其他玩家跟随到游戏的人很有用。

您可以使用此用户ID和 Players:GetNameFromUserIdAsync() 函数来获取玩家的名称。

代码示例

Followed Alert

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local function onPlayerAdded(newPlayer)
if newPlayer.FollowUserId == player.UserId then
local hint = Instance.new("Hint")
hint.Parent = player:WaitForChild("PlayerGui")
hint.Text = "You were followed to this game by " .. newPlayer.Name .. "!"
task.delay(3, function()
if hint then
hint:Destroy()
end
end)
end
end
Players.PlayerAdded:Connect(onPlayerAdded)

GameplayPaused

无法获知安全性
读取并联

GameplayPaused属性表示玩家当前在有StreamingEnabled启用的地方是否处于暂停状态。它是在客户端上设置的,但复制到服务器。要确定暂停状态,您可以使用此属性。

还请参阅:

HasVerifiedBadge

读取并联

Class.Player 属性表示玩家是否拥有验证徽章。

HealthDisplayDistance

读取并联

Class.Player 属性设置在 0 距离,其他 Humanoid 生命值栏将在所选健康条中显示. 如果设置为 0,生命值栏将不显示. 此属性默认为 StarterPlayer.HealthDisplayDistance

如果显示有人形体的生命值条,您可以使用 Humanoid.DisplayDistanceType 来设置显示类型。

代码示例

Hiding Player Health and Names

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0

LocaleId

隐藏
只读
未复制
读取并联

Class.Player 属性显示本地玩家为其 Roblox 帐户设置的本地语言 id。它包含两个字母代码(例如“en-us”)用于本地。

此属性可用于确定游戏玩家基地的地理数据,也是用于自动本地化(见GuiBase2d.AutoLocalize)的内容的本地语言。此属性允许访问服务器的本地语言。

还请参阅LocalizationService.RobloxLocaleId,用于本地化内容的本地化地点ID。当Roblox还没有内部支持本地玩家的设置地点时,这将是一个不同的值。

代码示例

Checking a Player's Locale

local Players = game:GetService("Players")
local player = Players.LocalPlayer
print(player.LocaleId)

MembershipType

只读
未复制
读取并联

此属性只能从以下方法读取以确定会员资格(它不能设为其他会员输入):它持有一个 Enum.MembershipType 枚帐户会员输入的枚数。

代码示例

Check Player Membership Status

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 属性设置在 0 秒后此玩家会看到其他 Humanoid 名称。如果属性设置为 0,名称将隐藏。此属性默认为 StarterPlayer.NameDisplayDistance

如果显示有人形体的生命值条,您可以使用 Humanoid.DisplayDistanceType 来设置显示类型。

代码示例

Hiding Player Health and Names

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0

Neutral

读取并联

中立属性确定玩家是否在特定团队上。

  • true 时,玩家不在特定团队上。这也意味着 Player.Team 属性将为空,而 Player.TeamColor 将为白色。
  • 当 为 时,玩家在特定团队上。 Player.Team 属性将与玩家所在的团队对应, Team

代码示例

Checking if a Player is Neutral

local Players = game:GetService("Players")
local player = Players.LocalPlayer
if player.Neutral then
print("Player is neutral!")
else
print("Player is not neutral!")
end

ReplicationFocus

读取并联

复制聚焦 Player 属性将零件聚焦在玩家周围。不同的 Roblox 系统在网络上通信(例如物理、流媒体等)复制在不同的速率依赖于物体是否靠近复制焦点。

当此属性为零时,它将恢复到默认行为,即将本地玩家的角色的 PrimaryPart 作为重复焦点。

此属性仅在服务器上设置有 Script ,而不是 LocalScript 。 注意到,此属性不会更改或更新零件的网络所有权。

代码示例

Setting a Player's 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 重生。 此属性只能通过 Lua 设置,并且必须包含有效的 SpawnLocation 的引用,该引用必须满足以下要求:

如果没有设置 RespawnLocation 为有效的 SpawnLocation ,那么默认的重生逻辑将适用。有关更多信息,请参阅页面上的 SpawnLocation

RespawnLocation 的替代

代码示例

Change Spawn on Touch

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

Team

未复制
读取并联

团队属性是一个引用于 Teams 服务中的对象,它确定玩家所在的团

代码示例

Playing/Spectating Teams

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)
Join Team Command

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 。 如果没有团队对象有联系的团队颜色,玩家将不会

通常来说,设置 Player.Team 到各自的 Team 而不是使用此属性是更好的选择。设置此属性通常会导致在多个脚本中重复使用相同的 BrickColor 值;这是您在遵循“不要重复自己”(DRY)原则时需要避免的事情。

代码示例

Playing/Spectating Teams

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)

UserId

读取并联

UserId 是一个 Player 属性,其中包含一个只读的整数,它 独一无二 地识别每个用户帐户在 Roblox 上。与玩家的 Instance.Name 不同,这值永远不会改变到同一个用户名户。

当保存/加载玩家数据时,使用 GlobalDataStores 的玩家数据存储器钥匙,以便每个玩家都有独特的键。

代码示例

Player.UserId

local Players = game:GetService("Players")
local function onPlayerAdded(player)
print(player.UserId)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Players:GetPlayerByUserId

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
Met the Creator Badge

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)
Data Store to Leaderboard

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

void

清除玩家色外观功能将所有 AccessoryShirtPants , 2>Class.CharacterMesh2> 和 <

它不会移除 t-shirts ,头部网格或面部。


返回

void

代码示例

How to Clear a Character's Appearance

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

Class.Player 函数将从角色头到指定 Vector3 点之间的距离返回给玩家。如果玩家没有 Player.Character ,它将返回 0。

这有助于确定游戏家和其他对象或地点之间的距离。

如果您想确定两个非玩家实例或位置之间的距离,您可以使用以关注中/正在关注:


local distance = (position1 - position2).magnitude

参数

point: Vector3

正在测量玩家的距离的位置。


返回

玩家和位置之间的距离。

代码示例

Measuring the Distance Between a Player and a Position

local Players = game:GetService("Players")
for _, player in pairs(Players:GetPlayers()) do
print(player:DistanceFromCharacter(Vector3.new(0, 0, 0)))
end

GetJoinData

返回一个包含描述玩家如何加入体验的典礼的字典。字典包含以下任意字段:


<tbody>
<tr>
<th>源游戏ID</th>
<td>数</td>
<td>体验的<code>Class.DataModel.GameId</code>。仅在玩家传送到当前体验时才会显示。</td>
</tr>
<tr>
<th>源地点Id</th>
<td>数</td>
<td>Class.DataModel.PlaceId 的地方,从 которого телепортируется <code>Player</code>。只有现在,如果玩家传送到当前位置并服务器调用传送函数,才会显示。</td>
</tr>
<tr>
<th>玩家ID</th>
<td>数</td>
<td>玩家邀请当前玩家体验。使用此数据识别参与者并触发奖励逻辑。</td>
</tr>
<tr>
<th>成员</th>
<td>阵数组</td>
<td>一个包含 <code>Class.Player.UserId</code> 的用户传送到 Player 旁边的数量。 仅在玩家传送为群组的一部分时才会显示。</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/deeplinking.md">深链接</a> URL 或 <code>Class.ExperienceInviteOptions.LaunchData</code> 中指定的发射数据。</td>
</tr>
</tbody>
钥匙值类型描述

获取加入数据和传送数据

如果服务器启动玩家的传送,该该方法返回的字典包含玩家的传送数据。 Player:GetJoinData() 方法只能用于在服务器上获取传送数据。 要获取客户端上的数据,请使用 TeleportService:GetLocalPlayerTeleportData()

TeleportService:GetLocalPlayerTeleportData() 不同,Player:GetJoinData() 只提供满足以下安全要求的传送数据:

  • 它确保已发送到 Roblox 服务器在过去 48 小时内。
  • 它保证已发送使用此 Player
  • SourcePlaceId 和 SourceGameId 保证都是来自数据发送地点和宇宙的。这意味着您可以验证传送数据是否来自一个批准的场景。

由于客户端发送此数据,它仍然可能被恶意玩家滥用。 敏感数据,例如玩家货币,应该通过安全解决方案,例如 Memory Stores 传输。


返回

一个包含 PlaceId 和 UserId 值的字典(见表在描述中)。

代码示例

Tracking Traffic Sources

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)
Referral URL Generator

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)
Using a Table as Launch Data

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
Decoding JSON Launch Data

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)
Server TeleportData Example

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 。玩家的鼠标实例可以用于跟踪用户鼠标输入包括左键和右键鼠标按钮点击和移动和位置。

Class.UserInputService 服务提供额外的函数和事件来跟踪用户输入 - 特别是那些不使用鼠标的设备。

注意:

  • 此项目 必须LocalScript 中使用,以便在线上工作如预期。
  • 2014年7月的更新后,鼠标的图标现在可以使用此方法设置。

返回

代码示例

How to Track Mouse Input

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 在秒内的独立网络延迟。 “Ping” 是一种测量数据从客户端发送到服务器,然后返回的时间的测量。它不涉及数据的解码或处理。

对于客户端 LocalScripts ,此函数仅可在 Players.LocalPlayer 上调用。此函数对于在高网络延迟场景中发生的问题的诊断和调试非常有用。它还有助于隐藏延迟,例如调整投掷动画的速度为рое子弹。


返回

HasAppearanceLoaded

HasAppearanceLoaded Player 函数返回玩家的 Player.Character 是否已加载。

玩家的外观包括玩家的 ShirtPantsAccessories

这很有用,当确定游戏家的外观是否已经加载,玩家可以使用 Players.PlayerAdded 事件来跟踪。


返回

一个Boolean指示是否加载玩家角色的外观。

代码示例

Check if a 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电话号码或政府ID验证。

当实现 IsVerified 时,请 exercise 小心确保实现不会不小心阻止所有未验证用户。

注意,该方法只能在后端服务器上调用。调用它从客户端会返回一个错误。此外,此方法在 Studio 中总是会返回 false


返回

一个指示玩家是否验证的Boolean。

代码示例

Using IsVerified

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

void

Class.Player.Kick|Kick() 方法允许体验雅致地连接一个客户端,并在不连接用户的选项下提供一条消息给不连接用户。 这对于滥用用户的管理非常有用。 您只应允许您信任的用户触发此方法在其他用户上。

调用此方法在 Player 上无参数地连接用户从服务器,并提供默认的注意消信息。 调用此方法在 Player 上,以及一个字符串作为第一个参数,替换默认消息提供给予的字符串。

使用此方法从 LocalScript ,只有本地用户的客户端才能被踢出。

参数

message: string

用户在踢出时显示的消息。

默认值:""

返回

void

Move

void

移动Player 函数使玩家的角色在指定方向上走路直到停止或被玩家中断(使用其控制)。

这很有用,当脚本 NPC Humanoids 在地图上移动时 - 但不是由实际玩家的输入控制。

注意,该函数的第二个参数表示是否将提供的 Vector3 移动到世界坐标 ( 否 ) 或玩家的 Camera ( 2> 是2> ) 。

参数

walkDirection: Vector3

玩家应该移动工具的向量3。

relativeToCamera: bool

一个指示玩家与玩家相对位置移动的Boolean。

默认值:false

返回

void

代码示例

Moving the Player relative to their Camera

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

void
插件安全性

SetAccountAge 函数设置玩家在天数内的 Player.AccountAge

它用于设置 Player 属性,该属性描述玩家的帐户在几天内注册时间。

这不会设置玩家在帐户上的年龄,但帐户自身的年龄相对于它创建时首次创建时的年龄。

参数

accountAge: number

帐户的年龄在天数。


返回

void

代码示例

Setting the Player's Account Age

local Players = game:GetService("Players")
local player = Players.LocalPlayer
player:SetAccountAge(100)
Account Age Mark

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

void
插件安全性

此方法设置玩家是否会看到通过 TextService:FilterStringAsync() 过滤的聊天,而不是正常聊天。


local Players = game:GetService("Players")
local player = Players.LocalPlayer
player:SetSuperSafeChat(true)

无论玩家是否启用过滤聊天,所有聊天都应该通过 TextService 来过滤,当播放到其他玩家或在玩家自己的屏幕上时。 TextService:FilterStringAsync() 返回一个 TextFilterResult 对象,可以根据消信息的用途不同进行过滤。

参数

value: bool

一个Boolean表示是否或不是否显示过滤器聊天。


返回

void

GetFriendsOnline

暂停

此函数返回一个在线好友的字典阵列,由 maxFriends 值限制。该函数使用 30 秒的内存池。

在返回的数组中,一些字段仅在某些位置类型上存在。例如,PlaceId在移动网站为 0 时不会存在。


<tbody>
<tr>
<td><b>访客ID</b></td>
<td>数</td>
<td>Class.Player.UserId 的朋好友。</td>
</tr>
<tr>
<td><b>用户名</b></td>
<td>字符串</td>
<td>朋好友的用户名。</td>
</tr>
<tr>
<td><b>显示名称</b></td>
<td>字符串</td>
<td>Class.Player.DisplayName 的朋好友。</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>朋好友的最后位置的数据模型/工作 id。</td>
</tr>
<tr>
<td><b>地点类型</b></td>
<td>数</td>
<td>
朋好友上次位置的地点类型:
<table>
0 > 移动网站 > 1> 移动游戏1> >0> 3> 13> >2> 6> 2</
</table>
</td>
</tr>
</tbody>
名称类型描述

参数

maxFriends: number

返回传的最大朋友数。

默认值:200

返回

一个在线朋友的字典(请参阅上表)。

代码示例

Get a List of Online Friends

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 仍然会认为他们在该群组中直到他们离开。但此不会在使用本地脚本时发生。

这是因为方法存储结果,因此多次调用 GetRankInGroup 上同一位玩家使用同一组 ID 会产生与方法首次调用时相同的结果。该 caching 行为基于每个 peer 的基础:服务器不会共享同一个缓存基础。

参数

groupId: number

指定群组的 groupId


返回

玩家在群组中的排名。

代码示例

How to Check a Player's Rank in a Group

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 函数将玩家的角色在群组中返回为字符串,或 Guest 如果玩家不是群组的一部分。

使用这在 Script ,而不是 LocalScript ,将不会让您获得最新的信息。如果玩家在游戏中离开群组,GetRoleInGroup 仍然会认为他们在该群组中,直到他们离开。但此不会发生在使用本地脚本的情况下。

这是因为方法会存储结果,因此多次调用 GetRoleInGroup 上同一位玩家使用同一组 ID 会产生与方法首次调用时相同的结果。该行为是基于每个服务器的:服务器不会共享同一个缓存基础:服务器不会共享一个客户端的同一个缓存基础。

参数

groupId: number

指定群组的 groupId


返回

玩家在指定群组中的角色,或 游客 如果玩家不是成会员 / 成员。

代码示例

How to Check a Player's Role in a Group

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 中使用时不会发生。

参数

userId: number

指定玩家的 Player.UserId


返回

一个指示玩家是否是指定用户的朋友的Boolean。

代码示例

How to Check if a Player is a Friend

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 仍然会认为他们在该群组中直到他们离开。但使用本地脚本时不会发生这种情况。

这是因为方法存储结果,因此多次调用 IsInGroup 在同一位玩家上使用相同的组 ID 将产生与方法首次使用给定的组 ID 相同的结果。该缓存行为基于每个 peer 的基础:服务器不会与客户端共享相同的缓存。

参数

groupId: number

指定群组的 groupId


返回

一个指示玩家是否在指定群组中的Boolean。

代码示例

How to Check if a Player is in a Group

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

void
暂停

LoadCharacter Player 函数为玩家创建一个新角色,移除旧角色。它还清除玩家的 BackpackPlayerGui

这对于你想要在不杀死玩家的情况下重新加载角色的情况有用,例如当你想要在更改玩家的 Player.CharacterAppearance 后加载一个新角色的外观。

注意:函数与 Player:LoadCharacterBlocking() 类似,但请求是处理异步而不是同步。这意味着其他任务可以在加载角色时继续,包括游戏的渲染和任何其他任务。还意味着这个函数在脚本中使用,而 LoadCharacterBlocking 不能。

在为单个玩家调用 LoadCharacter 之后,不建议再次调用它,直到玩家的 Player.CharacterAppearanceLoaded 事件发生后。

角色加载事件顺序

调用 Player:LoadCharacter() 用 R15 虚拟形象发生以下事件(注意:R6 顺序不同):

  1. Player.Character 设置
  2. Player.Character添加了火焰
  3. Player.Changed 会触发一个值为 “Character” 的
  4. 角色外观初始化
  5. Player.CharacterAppearanceLoaded 火焰
  6. Character.Parent 设置为 DataModel
  7. 角色网格模型和角色缩放模型
  8. 角色移动到生成地点
  9. LoadCharacter 返回

返回

void

代码示例

Turn Off Auto-Loading and Simulate Character Respawn

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

void
暂停

此函数生成一个虚拟形象,所以它有所有装备在 HumanoidDescription 中。

在为单个玩家调用 LoadCharacterWithHumanoidDescription 之后,不建议再次调用该玩家的 Player.CharacterAppearanceLoaded 事件,直到该玩家的 Class.Player.Character 事件发生后。

还请参阅:

  • 人形描述系统,一篇文章,解释了人形描述系统的更高级描述,并提供了几个脚本示例

参数

humanoidDescription: HumanoidDescription

一个 HumanoidDescription 包含身体部位/颜色、身体缩放、配件、服装和动画,将装备到载入角色。


返回

void

代码示例

Spawn Characters With HumanoidDescription

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

void
暂停

对于启用 实例投播 的体验,请注意,服务器的流量会流向指定的 XY 、 1> Z1> 位置的玩家区世界。如果体验知道玩家的 4>Datatype.

此调用的效果将是暂时的,并且没有保证将在指定位置流量会发生在哪里。客户端内存限制和网络条件可能会影响客户端可用性。

使用精autobion

要求在一个区域周围的流媒体是 不是保证 内容在请求完成时会存在,因为流媒体受到客户端的网络带宽、记忆限制和其他因素的影响。

参数

position: Vector3

请求流媒体的世界地点。

timeOut: number

可选的请求过期时间。

默认值:0

返回

void

活动

CharacterAdded

当玩家的角色生成时(或重生)时, 角色添加 事件触发。 此事件发生不久后将设置 Player.Character 为非 nil 值或调用 2>Class.Player:LoadCharacter()2>,这是角色在 5>Class.工作间orkspace5> 之前。

这些事件可以与 Player.CharacterRemoving 事件搭配使用,通常在玩家角色即将被移除的情况下发生,通常在死亡后。 因此,这些事件可能会发生多次,当玩家死亡然后重生在一个场景方。 要检测玩家是否加入或离开游戏时,请使用

注意,Humanoid和其默认身体部分(头、躯干和手足)将在此事件触发时存在,但服装项目,例如Class.Hat|Hats</

参数

character: Model

一个生成/重生该角色的实例。


代码示例

Detecting Player Spawns and Despawns

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)
Respawn at Despawn Location

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)
Accessory Remover

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 的完整外观已插入时,此事件会触发。

一般来说,Player.Character 具有一个范围内的对象修改其外观的对象,包括AccoutrementsShirts、2>Class.Pants2> 和 5>Class.CharacterMesh|CharacterMeshes

此事件的一个使用是确保所有配件在被销毁之前已加载。请参阅下面的示例。

参数

character: Model

Class.Player.Character Model


代码示例

Remove Accessories After Loading

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 的 Class.Player 。如果您需要跟踪玩家是否加入/离开游戏,请使用 Class.Players.PlayerAdded 和 Class.Players.PlayerRemoving 事件。

参数

character: Model

一个正在删除的角色的实例。


代码示例

Player.CharacterRemoving

game.Players.PlayerAdded:Connect(function(player)
player.CharacterRemoving:Connect(function(character)
print(character.Name .. " has died.")
end)
end)

Chatted

聊天事件触发,当 Player 键入了一条消息,并按“StarterGui:SetCoreGuiEnabled()”在 Roblox 的聊天栏中。这是使用默认聊天脚本的一些 Lua 绑定来实现的。您可以使用 Enum.CoreGuiType 来防止玩家聊天,并禁用聊天 2> Enum.CoreGuiType2> 。

聊天指令

使用这个事信息和一些像 string.sub()string.lower() 这样的字符串操作,可以创建聊天命令,甚至包含玩家名称。通常,命令的前缀是

过滤

使用此事件发射的消息文本是 未过滤 。如果您正在显示玩家输入,例如聊天给其他玩家,它必须使用 Chat:FilterStringAsync() 过滤。请记住,当您创建您自己的聊天系统时,如果您的游戏未能正确过滤聊天,可能会导致对它的审核操作。

参数

message: string

玩家在聊天中输入的内容。

recipient: Player

已弃用。 对于 Whisper 消息,这是聊天消信息的目标。


代码示例

Player.Chatted

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)
Playing/Spectating Teams

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)
Join Team Command

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 的发生相关联。

参数

time: number

玩家在秒内的空闲置时间。


代码示例

Player.Idled

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

发生在玩家的传送状态变更时。 此事件有助于检测是否成功传送。

什么是 TeleportState?

使用 TeleportService 发出传送请求时,会有一系列在 Player 传送之前的阶段。当前阶段由 OnTeleport 提供的值表示为 Enum.TeleportState 。请参阅以下示例。

参数

teleportState: Enum.TeleportState

Class.Player 的新 Player .

placeId: number

Class.Player 正在传送到的地方的 ID。

spawnName: string

如果 TeleportService:TeleportToSpawnByName() 已被使用,该生成器的名称。


代码示例

Player.OnTeleport

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)