Players

显示已弃用

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

无法创建
服务

Players 服务包含 Player 对于目前连接到 Roblox 服务器的客户端的对象。它还包含有关场景点配置的信息。它可以检索不连接到服务器的玩家的信息,例如角色外观、好友和虚拟形象缩略图。

概要

属性

方法

活动

属性

BanningEnabled

未复制
不可写入脚本
读取并联

启用或禁用构成禁止 API 的三个 Players 方法 ( BanAsync() , UnbanAsync() , 和 GetBanHistoryAsync() )此属性不可脚本化,只能在工作室中修改。

BubbleChat

只读
未复制
读取并联

此属性表示是否启用泡泡聊天。它使用 Players:SetChatStyle() 枚列设置,使用 Enum.ChatStyle 枚列启用或禁用泡泡聊天。

启用聊天模式时,游戏将聊天用户界面显示在屏幕左上角。

还有两种其他聊天模式,Players.ClassicChat 和启用了两种经典和泡泡聊天的聊天模式。

CharacterAutoLoads

未复制
读取并联

该属性表示 whether characters 是否会自动重生。默认值为 true。

如果此属性被禁用(false),玩家 不会在每次调用 函数时生成,包括当玩家加入体验时。

这可能对那些经验有用,在那些经验中玩家的生命是有限的,例如那些玩家在游戏回合结束之前不会重生的竞争游戏。

代码示例

This example demonstrates one possible usage of the Players.CharacterAutoLoads property.

The example below respawns all players in the game, if dead, once every 10 seconds. This means that players who die 1 second after all players respawn must wait 9 seconds until the script loads all Player.Character again.

First, this script removes a player's character when they die and the Humanoid.Died function fires. This is done so that the respawn loop that executes every 10 seconds reloads that player when it does not find the player's character in the Workspace.

To work as expected, this example should be run within a Script.

Player Respawn Timer

local Players = game:GetService("Players")
-- Set CharacterAutoLoads to false
Players.CharacterAutoLoads = false
-- Remove player's character from workspace on death
Players.PlayerAdded:Connect(function(player)
while true do
local char = player.CharacterAdded:Wait()
char.Humanoid.Died:Connect(function()
char:Destroy()
end)
end
end)
-- Respawn all dead players once every 10 seconds
while true do
local players = Players:GetChildren()
-- Check if each player is dead by checking if they have no character, if dead load that player's character
for _, player in pairs(players) do
if not workspace:FindFirstChild(player.Name) then
player:LoadCharacter()
end
end
-- Wait 10 seconds until next respawn check
task.wait(10)
end

ClassicChat

只读
未复制
读取并联

指示是否启用经典聊天。此属性由 Players:SetChatStyle() 方法使用枚举 Enum.ChatStyle 设置。

启用聊天模式时,游戏会在发送者头顶上的泡泡显示聊天内容。

还有两种其他聊天模式,Players.BubbleChat 和启用了两种经典和泡泡聊天的聊天模式。

LocalPlayer

只读
未复制
读取并联

这个仅读取属性指的是 Player 的客户端运行体验。

该属性仅为 LocalScriptsModuleScripts 所需定义,因为它们运行在客户端上。对于服务器,在哪个 Script 对象运行代验证码,此属性是 nil

MaxPlayers

只读
未复制
读取并联

该属性决定服务器上最多可以容纳的玩家数量。此属性只能通过 创建者面板 上特定场景点的设置或 游戏设置 设置来设置。

PreferredPlayers

只读
未复制
读取并联

该属性表示 Roblox 的匹配器将填充服务器的玩家数量。这个数字将小于体验支持的最大玩家数(Players.MaxPlayers)。

RespawnTime

读取并联

该属性控制时间,以秒为单位,当 Players.CharacterAutoLoads 为真时,玩家重生所需的时间。默认值为 5.0 秒。

当你想要根据体验类型改变重生所需时间,但不想单独处理重生玩家时,这很有用。

虽然这个属性可以从 中设置,但您可以更轻松地直接在 Studio 的 窗口中设置它。

UseStrafingAnimations

不可写入脚本
读取并联

方法

Chat

()
插件安全性

这个函数使本地玩家聊天给定的消信息。由于该物品受到保护,尝试在 ScriptLocalScript 中使用将导致错误。

当创建自定义聊天系统或需要访问聊天的系统时,您可以使用 Chat 服务的 Chat:Chat() 函数来进行替换。

参数

message: string

聊天的消息。

默认值:""

返回

()

代码示例

This example demonstrates that the Players:Chat() function executes without error if using the Command Bar or a Plugin (assuming the local player can chat freely) and errors if executed in a Script.

Players:Chat

-- Command bar
game:GetService("Players"):Chat("Hello, world!") --Results in 'Hello, world!' appearing in the Chat log under your Player's name.
-- Script
local Players = game:GetService("Players")
Players:Chat("Hello, world!") --Errors

GetPlayerByUserId

写入并联

此函数搜索每个 在 中找到一个与给定的 匹配的人。如果这样的玩家不存在,它将返回 nil

这种方法对于使用 MarketplaceService.ProcessReceipt 找到开发者产品的购买者有用,该方法提供一个包含购买者 UserId 和不指向 Player 对象本身的表。大多数体验都需要对玩家进行引用以授予产品。

参数

userId: number

指定玩家的 Player.UserId

默认值:""

返回

代码示例

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

GetPlayerFromCharacter

此函数返回与给定 Player 相关的 Player.Characternil ,如果无法找到,则返回。它相当于以下函数:


local function getPlayerFromCharacter(character)
for _, player in game:GetService("Players"):GetPlayers() do
if player.Character == character then
return player
end
end
end

此方法通常在玩家角色中发生某些事件时使用(例如他们的 Humanoid dying)。这样的事件可能不直接引用玩家对象,但这种方法提供了简单的访1) 使用权 2)通行证 3)访问权限。这个函数的反义可以描述为获取玩家的角色。要做到这一点,只需访问角色属性。

参数

character: Model

你想从中获得玩家的角色实例。

默认值:""

返回

代码示例

Players:GetPlayerFromCharacter

Players:GetPlayerFromCharacter

local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local PLAYER_NAME = "Nightriff"
local character = Workspace:FindFirstChild(PLAYER_NAME)
local player = Players:GetPlayerFromCharacter(character)
if player then
print(`Player {player.Name} ({player.UserId}) is in the game`)
else
print(`Player {PLAYER_NAME} is not in the game!`)
end

GetPlayers

Instances
写入并联

该方法返回所有现在连接的 Player 对象的表。它的功能与 Instance:GetChildren() 相同,除了它只返回 PlayerPlayers 下找到的对象。当与 for 循环一起使用时,它对游戏中的所有玩家进行循环有用。


local Players = game:GetService("Players")
for _, player in Players:GetPlayers() do
print(player.Name)
end

连接到 Players.PlayerAdded 的脚本经常尝试处理每个连接到游戏的玩家。这个方法对于已连接但不会发射 PlayerAdded 的玩家有用。使用此方法可确保没有玩家被错过!


local Players = game:GetService("Players")
local function onPlayerAdded(player)
print("Player: " .. player.Name)
end
for _, player in Players:GetPlayers() do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)

返回

Instances

包含服务器上所有玩家的表。

代码示例

This code sample listens for players spawning and gives them Sparkles in their head. It does this by defining two functions, onPlayerSpawned and onPlayerAdded.

Give Sparkles to Everyone

local Players = game:GetService("Players")
local function onCharacterAdded(character)
-- Give them sparkles on their head if they don't have them yet
if not character:FindFirstChild("Sparkles") then
local sparkles = Instance.new("Sparkles")
sparkles.Parent = character:WaitForChild("Head")
end
end
local function onPlayerAdded(player)
-- Check if they already spawned in
if player.Character then
onCharacterAdded(player.Character)
end
-- Listen for the player (re)spawning
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)

SetChatStyle

()
插件安全性

这个函数设置是否使用 BubbleChat 和 ClassicChat,并告诉团队聊天和聊天使用枚举 Enum.ChatStyle 做什么。由于该物品受到保护,尝试在 ScriptLocalScript 中使用将导致错误。

当聊天模式由游戏设置时,该函数在内部使用。

参数

指定的聊天风格正在设置。

默认值:"Classic"

返回

()

代码示例

This example demonstrates that the Players:SetChatStyle() function executes without error if using the Command Bar or a Plugin and errors if executed in a LocalScript.

When executed in the Command Bar, this code sets the chat style to Classic using the Enum.ChatStyle enum.

Setting a Player's Chat Style

-- Command bar
game.Players:SetChatStyle(Enum.ChatStyle.Classic) -- Set's chat style to Classic
-- LocalScript
local Players = game:GetService("Players")
Players:SetChatStyle(Enum.ChatStyle.Classic) -- Errors

TeamChat

()
插件安全性

这个函数使 Players.LocalPlayer 聊天发送给指定的信息,只有相同团队的用户才能查看。由于该物品受到保护,尝试在 ScriptLocalScript 中使用将导致错误。

Players.LocalPlayer 向其团队发送消息时,内部使用此函数。

参数

message: string

聊天中的消息。

默认值:""

返回

()

代码示例

This example demonstrates that the Players:TeamChat() function executes without error if using the Command Bar or a Plugin and errors if executed in a LocalScript.

When executed in the Command Bar, the function sends the specified message to all players on the same Team as the Players.LocalPlayer.

Sending Team Chat

-- Command bar
game.Players:TeamChat("Hello World") -- Sends a "Hello World" message to all players on the local player's team
-- LocalScript
local Players = game:GetService("Players")
Players:TeamChat("Hello World") -- Errors

BanAsync

()
暂停

Players:BanAsync() 方法可以让你轻松禁止那些违反你体验指南的用户。您可以指定禁止时间长度,启用禁止向怀疑的替换帐户传播,并根据使用指南为禁止用户提供消息。你还应该在所有用户都能访问的地方发布你的经验规则,并提供一个让他们提出上申诉的方式。此方法由 Players.BanningEnabled 属性启用和禁用,您可以在 Studio 中切换。

禁止和消息传递

被禁止的用户将立即驱逐,并且不能重新加入您的体验。他们将被提供一个错误模块,显示他们禁止的时间和你的 DisplayReason 。Roblox 的后端系统将驱逐玩家从所有服务器中驱逐到你指定的场景点(们)。DisplayReason 最长可达 400 个字符,并受到文本过过滤器。了解有关可接受模态文本的更多信息,请参阅禁止消息传递

地点和宇宙

默认情况下,禁令扩展到该宇宙内的任何地方。要限制禁令仅限于那个地方,从而仅调用此 API,配置 ApplyToUniversefalse .然而,如果用户在宇宙的起始地点被禁止,它实际上会导致用户被排除出宇宙的全部,无论是否存在通用禁令。

替代帐户

用户经常在多个不同帐户下进行游戏,也称为替换帐户或备选帐户,这些帐户有时用于旁路帐户禁令。为了帮助您保持禁止用户出局,此 API 的默认行为将将所有禁令从您禁止的源帐户传播到任何怀疑的替代帐户。您可以通过配置 ExcludeAltAccountstrue 来关闭禁止传播到替换帐户。

禁止时长

不是所有的违规都相同,所以不是所有的禁令都应该相同长度。此 API 允许您在秒内配置封停令时间,使用 Duration 字段。要指定永久封封停,将字段设置为 -1 。您还可能想要基于用户的禁令历史动态配置禁令期限,您可以使用 Players:GetBanHistoryAsync() 来查询。例如,你可能想考虑禁令数量、以前禁令的持续时间或建造逻辑,从你保存在 PrivateReason 下的笔记中,这些笔记最多可能有 1000 个字符,不会被文本过滤。PrivateReason 笔记永远不会与客户端共享,可以认为是免于攻击者的。

错误和限速

该方法调用后端服务的 HTTP 请求,可能会导致限制并可能会失败。如果您使用多于一个 UserId 调用此 API,该方法将尝试为每个 ID 发送 HTTP 请求。然后将聚合任何错误消息,并将它们组合为以逗号分开列表。例如,如果这个方法被调用给五个用户,并且要求那些拥有 UserIds 2 和 4 的人失败,以下错误消息出现:

HTTP failure for UserId 2: Timedout, HTTP 504 (Service unavailable) failure for UserId 4: Service exception

消息总是包含 failure for UserId {} 如果它是 HTTP 错误。

客户端要求

由于与禁止用户相关的风险,此方法只能在后端体验服务器(客户端调用会导致错误)上调用。您可以在 Studio 中测试此 API,在 协作 作品期间或在 团队测试 期间进行测试,但禁令不适用于生产。

此 API 使用了 用户限制开放云 API。你可以使用这些 API 来在第三方应用程序中管理你的禁令。

参数

config: Dictionary
  • UserIds (必需;阵数组)—禁止的玩家数量为 UserIds 的阵列。最大尺寸为 50

  • ApplyToUniverse (可选; boolean)—禁令是否传播到体验宇宙内的所有地方。默认值为 true

  • Duration (必填;整数)—封停令时间,以秒为单位。永久封禁应具有值 -10和所有其他负值无效。

  • DisplayReason (必填;字符串) — 用户尝试加入体验并失败时显示给用户的消息。最大字符长度为 400

  • PrivateReason (必填;字符串) — 用户禁令历史查询返回的内部消息。最大字符串长度为 1000

  • ExcludeAltAccounts (可选; boolean) — 当 true 时,Roblox不会尝试禁止替换帐户。默认值为false

默认值:""

返回

()

代码示例

The following example bans a user with a duration calculated from their ban history, scoped to the entire universe and all of the user's alternate accounts.

Banning Users

local Players = game:GetService("Players")
if shouldBeBanned(player) then
local banHistoryPages = Players:GetBanHistoryAsync(player.UserId)
local duration = getNextBanDuration(banHistoryPages) -- Creator-implemented logic
local config: BanConfigType = {
UserIds = { player.UserId },
Duration = duration,
DisplayReason = "You violated community guideline #5",
PrivateReason = "Put anything here that the user should not know but is helpful for your records",
ExcludeAltAccounts = false,
ApplyToUniverse = true,
}
local success, err = pcall(function()
return Players:BanAsync(config)
end)
print(success, err)
end

CreateHumanoidModelFromDescription

暂停

返回一个装备了 HumanoidDescription 中指定的所有内容的角色模型,并且由 rigType 指定为 R6 或 R15。

参数

description: HumanoidDescription

指定返回的字符的外观。

默认值:""

指定返回的角色是否为 R6 或 R15。

默认值:""
assetTypeVerification: Enum.AssetTypeVerification

资产类型验证决定这个函数是否会加载模型(你应该将其设置为永远,除非你想加载非目录资产)。

默认值:"Default"

返回

一个人形角色模型。

代码示例

This code sample creates a Humanoid Model from the passed in HumanoidDescription and parents the Model to the Workspace.

Create Humanoid Model From Description

game.Players:CreateHumanoidModelFromDescription(Instance.new("HumanoidDescription"), Enum.HumanoidRigType.R15).Parent =
game.Workspace

CreateHumanoidModelFromUserId

暂停

返回一个包含所有装备匹配用户指定的虚拟形象的角色模型设置。传入的 userId 指定了用户。这包括该角色目前是 R6 还是 R15。

参数

userId: number

Roblox 用户的用户ID。 (用户ID是用户个人资料中的数字,例如 www.roblox.com/users/1/profile)

默认值:""

返回

一个人形角色模型。

代码示例

This code sample creates a Humanoid Model to match the avatar of the passed in User ID, and parents the Model to the Workspace.

Create Humanoid Model From A User ID

game.Players:CreateHumanoidModelFromUserId(1).Parent = game.Workspace

GetBanHistoryAsync

暂停

检索体验宇宙内任何用户的封禁和解禁历史。该方法返回一个继承自 BanHistoryPages 的实例,该实例从 Pages 中继承。此方法由 Players.BanningEnabled 属性启用和禁用,您可以在 Studio 中切换。

此函数调用只能在生产游戏服务器上成功,而不是在客户端设备或 Studio 中。

此 API 使用了 用户限制开放云 API。你可以使用这些 API 来在第三方应用程序中管理你的禁令。

参数

userId: number
默认值:""

返回

BanHistoryPages 获取返回参考。

GetCharacterAppearanceInfoAsync

暂停

此函数返回关于玩家虚拟形象(忽略装备)的网站上Roblox网站的词典形式的信息。它不要与 GetCharacterAppearanceAsync 混淆,后者实际上加载了这个方法描述的资产。您可以使用 InsertService:LoadAsset() 来加载玩家的虚拟形象中使用的资产。返回的字典结构如下:


<th>类型</th>
<th>描述</th>
</tr>
</thead>
<tr>
<td><code>资产</code></td>
<td>表(见下面)</td>
<td>描述装备的资产(帽子、身体部件等)</td>
</tr>
<tr>
<td><code>身体颜色</code></td>
<td>表(见下面)</td>
<td>描述每个肢体的 BrickColor 值</td>
</tr>
<tr>
<td><code>身体颜色3秒</code></td>
<td>表(见下面)</td>
<td>描述每个肢体的颜色3实例,可能与身体颜色不完全匹配</td>
</tr>
<tr>
<td><code>默认裤子已应用</code></td>
<td>bool</td>
<td>描述是否应用默认裤子</td>
</tr>
<tr>
<td><code>默认衬衫应用</code></td>
<td>bool</td>
<td>描述是否应用默认衬衫</td>
</tr>
<tr>
<td><code>表情</code></td>
<td>表(见下面)</td>
<td>描述装备的表情动画</td>
</tr>
<tr>
<td><code>玩家虚拟形象类型</code></td>
<td>字符串</td>
<td>“R15”或“R6”</td>
</tr>
<tr>
<td><code>缩放</code></td>
<td>表(见下面)</td>
<td>描述各种身体缩放因素</td>
</tr>
名称
资产子表

assets 表是一个包含以下键描述玩家目前装备的资产的表阵列:


<th>类型</th>
<th>描述</th>
</tr>
</thead>
<tr>
<td><code>id</code></td>
<td>数字</td>
<td>装备的资素材 ID</td>
</tr>
<tr>
<td><code>资产类型</code></td>
<td>表</td>
<td>一个包含 <code>名称</code> 和 <code>ID</code> 字段的表,每个描述装备的类型("帽子", "脸"等)</td>
</tr>
<tr>
<td><code>名称</code></td>
<td>字符串</td>
<td>装备的资产名称</td>
</tr>
名称
缩放子表

scales 表有以下键,每个键对应一个 Humanoid 缩放属性:bodyType , head , height , proportion , depth , width .

身体颜色子表

bodyColors 表有以下键,每个键对应一个 BrickColor ID 号码,可以与 BrickColor.new(id) 一起使用:leftArmColorId , torsoColorId , rightArmColorId , headColorId , leftLegColorId , rightLegColorId .

参数

userId: number

指定玩家的* id

默认值:""

返回

包含给定用户角色外观信息的词典。

代码示例

Sometimes it is best to see an example of the returned dictionary structure in pure Lua. Here is one such example of a player whose avatar uses a package and wears several hats. Can you guess who it is?

Example Return Character Appearance Dictionary

local result = {
playerAvatarType = "R15",
defaultPantsApplied = false,
defaultShirtApplied = false,
scales = {
bodyType = 0,
head = 1,
height = 1.05,
proportion = 0,
depth = 0.92,
width = 0.85,
},
bodyColors = {
leftArmColorId = 1030,
torsoColorId = 1001,
rightArmColorId = 1030,
headColorId = 1030,
leftLegColorId = 1001,
rightLegColorId = 1001,
},
assets = {
{
id = 1031492,
assetType = {
name = "Hat",
id = 8,
},
name = "Striped Hat",
},
{
id = 13062491,
assetType = {
name = "Face Accessory",
id = 42,
},
name = "Vision Française ",
},
{
id = 16598440,
assetType = {
name = "Neck Accessory",
id = 43,
},
name = "Red Bow Tie",
},
{
id = 28999228,
assetType = {
name = "Face",
id = 18,
},
name = "Joyous Surprise",
},
{
id = 86896488,
assetType = {
name = "Shirt",
id = 11,
},
name = "Expensive Red Tuxedo Jacket",
},
{
id = 86896502,
assetType = {
name = "Pants",
id = 12,
},
name = "Expensive Red Tuxedo Pants",
},
{
id = 376530220,
assetType = {
name = "Left Arm",
id = 29,
},
name = "ROBLOX Boy Left Arm",
},
{
id = 376531012,
assetType = {
name = "Right Arm",
id = 28,
},
name = "ROBLOX Boy Right Arm",
},
{
id = 376531300,
assetType = {
name = "Left Leg",
id = 30,
},
name = "ROBLOX Boy Left Leg",
},
{
id = 376531703,
assetType = {
name = "Right Leg",
id = 31,
},
name = "ROBLOX Boy Right Leg",
},
{
id = 376532000,
assetType = {
name = "Torso",
id = 27,
},
name = "ROBLOX Boy Torso",
},
},
}
print(result)

GetFriendsAsync

暂停

GetFriends Players 函数返回包含所有指定用户朋友信息的对象 Class.FriendPages``Class.FriendPages 对象内的物品是具有以下字段的表:


<th>类型</th>
<th>描述</th>
</tr>
</thead>
<tr>
<td>Id</td>
<td>int64</td>
<td>朋好友的用户ID</td>
</tr>
<tr>
<td>用户名</td>
<td>字符串</td>
<td>朋好友的用户名</td>
</tr>
<tr>
<td>显示名称</td>
<td>字符串</td>
<td>朋好友的 <code>Class.Player.DisplayName|显示名称</code></td>
</tr>
名称

查看代码示例,了解一种简单的方法来遍历所有玩家的朋友。

参数

userId: number

指定玩家的用户 ID。

默认值:""

返回

代码示例

This code sample loads the Player.UserId of the player whose username is provided at the top of the script by using Players:GetUserIdFromNameAsync(). Then, it gets a FriendPages object by calling Players:GetFriendsAsync() and iterates over each entry using the iterPageItems function. The username of each friend is stored in a table, then printed at the end.

Print Roblox Friends

local Players = game:GetService("Players")
local USERNAME = "Cozecant"
local function iterPageItems(pages)
return coroutine.wrap(function()
local pagenum = 1
while true do
for _, item in ipairs(pages:GetCurrentPage()) do
coroutine.yield(item, pagenum)
end
if pages.IsFinished then
break
end
pages:AdvanceToNextPageAsync()
pagenum = pagenum + 1
end
end)
end
-- First, get the user ID of the player
local userId = Players:GetUserIdFromNameAsync(USERNAME)
-- Then, get a FriendPages object for their friends
local friendPages = Players:GetFriendsAsync(userId)
-- Iterate over the items in the pages. For FriendPages, these
-- are tables of information about the friend, including Username.
-- Collect each username in a table
local usernames = {}
for item, _pageNo in iterPageItems(friendPages) do
table.insert(usernames, item.Username)
end
print("Friends of " .. USERNAME .. ": " .. table.concat(usernames, ", "))

GetHumanoidDescriptionFromOutfitId

暂停

返回指定服装ID的 HumanoidDescription,该服装ID将与服装的零件/颜色/动画等设置。服装可以是用户创建的,也可以是 Roblox 创建的包装的服装。

参数

outfitId: number

寻找 HumanoidDescription 的服装的 id。

默认值:""

返回

用于传递的服装ID的规格初始化的人形描述。

代码示例

Shows how to get the HumanoidDescription for bundle 799 (Fishman).

Get HumanoidDescription From Outfit ID

local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local function getOutfitId(bundleId)
if bundleId <= 0 then
return
end
local info = game.AssetService:GetBundleDetailsAsync(bundleId)
if not info then
return
end
for _, item in pairs(info.Items) do
if item.Type == "UserOutfit" then
return item.Id
end
end
return nil
end
local function getHumanoidDescriptionBundle(bundleId)
local itemId = getOutfitId(bundleId)
if itemId and itemId > 0 then
return Players:GetHumanoidDescriptionFromOutfitId(itemId)
end
return nil
end
local humanoidDescription = getHumanoidDescriptionBundle(799)
local humanoidModel = Players:CreateHumanoidModelFromDescription(humanoidDescription, Enum.HumanoidRigType.R15)
humanoidModel.Parent = Workspace

GetHumanoidDescriptionFromUserId

暂停

返回一个 HumanoidDescription ,该描述指定了用户指定的虚拟形象所装备的一切。还包括尺寸和身体颜色。

参数

userId: number

Roblox 用户的用户ID。 (用户ID是用户个人资料中的数字,例如 www.roblox.com/users/1/profile)

默认值:""

返回

使用传入用户的虚拟形象规格初始化的人形描述。

代码示例

This code sample shows how to use GetHumanoidDescriptionFromUserId() to create a Humanoid Model.

Get HumanoidDescription From User ID

game.Players:CreateHumanoidModelFromDescription(
game.Players:GetHumanoidDescriptionFromUserId(1),
Enum.HumanoidRigType.R15
).Parent =
game.Workspace

GetNameFromUserIdAsync

暂停

GetNameFromUserIdAsync Players 函数将向 Roblox 网站发送查询,询问指定 UserId 的帐户用户名是什么。

如果没有与给定的用户ID相关的帐户存在,该方法将发生错误。如果你不确定是否存在这样的帐户,建议用 pcall() 来包装调用此函数的调用。此外,您可以手动缓存结果,以便将来使用相同的用户ID进行快速调用。查看代码示例了解更多信息。

参数

userId: number

指定玩家的 Player.UserId

默认值:""

返回

指定的 Player.UserId 的用户名。

代码示例

This code sample demonstrates using the Players:GetNameFromUserIdAsync() method to get a user's Player.Name from their Player.UserId.

Get Name from UserId

local Players = game:GetService("Players")
-- Example Data:
-- UserId: 118271 Name: "RobloxRulez"
-- UserId: 131963979 Name: "docsRule"
local nameOne = Players:GetNameFromUserIdAsync(118271)
local nameTwo = Players:GetNameFromUserIdAsync(131963979)
print(nameOne, nameTwo)
-- prints: "RobloxRulez docsRule"

This code sample demonstrates using the Players:GetNameFromUserIdAsync() method to get a user's Player.Name from their Player.UserId. Because GetNameFromUserIdAsync() yields, you can avoid calling it for the same Name using a table to store each UserId:Name pair found, called a cache. pcall() is used to catch the failure in case the Name doesn't exist.

Get Name from UserId using a cache

local Players = game:GetService("Players")
-- Create a table called 'cache' to store each 'Name' as they are found.
-- If we lookup a 'Name' using the same 'UserId', the 'Name' will come
-- from cache (fast) instead of GetNameFromUserIdAsync() (yields).
local cache = {}
function getNameFromUserId(userId)
-- First, check if the cache contains 'userId'
local nameFromCache = cache[userId]
if nameFromCache then
-- if a value was stored in the cache at key 'userId', then this 'nameFromCache'
-- is the correct Name and we can return it.
return nameFromCache
end
-- If here, 'userId' was not previously looked up and does not exist in the
-- cache. Now we need to use GetNameFromUserIdAsync() to look up the name
local name
local success, _ = pcall(function()
name = Players:GetNameFromUserIdAsync(userId)
end)
if success then
-- if 'success' is true, GetNameFromUserIdAsync() successfully found the
-- name. Store this name in the cache using 'userId' as the key so we
-- never have to look this name up in the future. Then return name.
cache[userId] = name
return name
end
-- If here, 'success' was false, meaning GetNameFromUserIdAsync()
-- was unable to find the 'name' for the 'userId' provided. Warn the user
-- this happened and then return nothing, or nil.
warn("Unable to find Name for UserId:", userId)
return nil
end
-- Example Data:
-- UserId: 118271 Name: "RobloxRulez"
-- UserId: 131963979 Name: "docsRule"
-- The first time a UserId is used, GetNameFromUserIdAsync() will be called
local nameOne = getNameFromUserId(118271)
local nameTwo = getNameFromUserId(131963979)
-- Because 118271 was previously used, get its Name from the cache
local nameOneQuick = getNameFromUserId(118271)
print(nameOne, nameTwo, nameOneQuick)
-- prints: "RobloxRulez docsRule RobloxRulez"

GetUserIdFromNameAsync

暂停

此函数将向 Roblox 网站发送查询,询问指定 Player.UserId 名称的帐户的 Player 是什么。

如果给定的用户名没有帐户存在,该方法将发生错误。如果你不确定是否存在这样的帐户,建议用 pcall() 来包装调用此函数的调用。此外,您可以手动缓存结果,以便快速使用相同的用户名进行未来的调用。查看代码示例了解更多信息。

参数

userName: string

指定玩家的用户名。

默认值:""

返回

指定名称的用户的 Player.UserId

代码示例

This code sample demonstrates using the Players:GetUserIdFromNameAsync() method to get a user's Player.UserId from their Player.Name.

Get UserId from Name

local Players = game:GetService("Players")
-- Example Data:
-- UserId: 118271 Name: "RobloxRulez"
-- UserId: 131963979 Name: "docsRule"
local userIdOne = Players:GetUserIdFromNameAsync("RobloxRulez")
local userIdTwo = Players:GetUserIdFromNameAsync("docsRule")
print(userIdOne, userIdTwo)
-- prints: "118271 131963979"

This code sample demonstrates using the Players:GetUserIdFromNameAsync() method to get a user's Player.UserId from their Player.Name. Because GetUserIdFromNameAsync() yields, you can avoid calling it for the same UserId using a table to store each Name:UserId pair found, called a cache. pcall() is used to catch the failure in case the UserId doesn't exist.

Get UserId from Name using a cache

local Players = game:GetService("Players")
-- Create a table called 'cache' to store each 'UserId' as they are found.
-- If we lookup a 'UserId' using the same 'Name', the 'UserId' will come
-- from cache (fast) instead of GetUserIdFromNameAsync() (yields).
local cache = {}
function getUserIdFromName(name)
-- First, check if the cache contains 'name'
local userIdFromCache = cache[name]
if userIdFromCache then
-- if a value was stored in the cache at key 'name', then this 'userIdFromCache'
-- is the correct UserId and we can return it.
return userIdFromCache
end
-- If here, 'name' was not previously looked up and does not exist in the
-- cache. Now we need to use GetUserIdFromNameAsync() to look up the userId
local userId
local success, _ = pcall(function()
userId = Players:GetUserIdFromNameAsync(name)
end)
if success then
-- if 'success' is true, GetUserIdFromNameAsync() successfully found the
-- userId. Store this userId in the cache using 'name' as the key so we
-- never have to look this userId up in the future. Then return userId.
cache[name] = userId
return userId
end
-- If here, 'success' was false, meaning GetUserIdFromNameAsync()
-- was unable to find the 'userId' for the 'name' provided. We can warn the
-- user this happened and then return nothing, or nil.
warn("Unable to find UserId for Name:", name)
return nil
end
-- Example Data:
-- UserId: 118271 Name: "RobloxRulez"
-- UserId: 131963979 Name: "docsRule"
-- The first time a Name is used, GetUserIdFromNameAsync() will be called
local userIdOne = getUserIdFromName("RobloxRulez")
local userIdTwo = getUserIdFromName("docsRule")
-- Because "RobloxRulez" was previously used, get its UserId from the cache
local userIdOneQuick = getUserIdFromName("RobloxRulez")
print(userIdOne, userIdTwo, userIdOneQuick)
-- prints: "118271 131963979 118271"

GetUserThumbnailAsync

暂停

此函数返回玩家的虚拟形象图像的内容 URL,给予其 UserId ,所需的图像尺寸作为 Enum.ThumbnailSize 枚数,以及所需的类型作为 Enum.ThumbnailType 枚数。它还返回一个描述图像是否准备使用的 boolean 值。

最常用的方法是使用 ImageLabel.ImageDecal.Texture 来显示用户虚拟形象图像在体验中。

参数

userId: number

指定玩家的 Player.UserId

默认值:""
thumbnailType: Enum.ThumbnailType

一个 Enum.ThumbnailType 描述缩略图类型的。

默认值:""
thumbnailSize: Enum.ThumbnailSize

A Enum.ThumbnailSize 指定缩略图的大小。

默认值:""

返回

包含指定参数的用户缩略图内容 URL 和描述图像是否准备好使用的 bool 的 tuple。

代码示例

This code sample displays the current player's thumbnail in a parent ImageLabel by using Players:GetUserThumbnailAsync() and setting the Image() property as well as its Size().

Display Player Thumbnail

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local PLACEHOLDER_IMAGE = "rbxassetid://0" -- replace with placeholder image
-- fetch the thumbnail
local userId = player.UserId
local thumbType = Enum.ThumbnailType.HeadShot
local thumbSize = Enum.ThumbnailSize.Size420x420
local content, isReady = Players:GetUserThumbnailAsync(userId, thumbType, thumbSize)
-- set the ImageLabel's content to the user thumbnail
local imageLabel = script.Parent
imageLabel.Image = (isReady and content) or PLACEHOLDER_IMAGE
imageLabel.Size = UDim2.new(0, 420, 0, 420)

UnbanAsync

()
暂停

解除玩家被禁止使用 Players:BanAsync()用户限制开放云 API 的禁令。此方法由 Players.BanningEnabled 属性启用和禁用,您可以在 Studio 中切换。

Players:BanAsync() 一样,这个方法接受一个 config 字典,可以让你批量解除用户的禁令。这配置了被解除禁令的用户和他们被解除禁令的范围。

解除禁令只会在具有相同 ApplyToUniverse 范围的禁令生效。例如,设置为 ApplyToUniverse 的解除封禁不会无效化以前设置为 true 的封禁,设置为 ApplyToUniverse 的设置为 false 的封禁。换言之,宇宙级别解禁不会无效化地点级别封停。相反的情况也是如此。

该方法调用后端服务的 HTTP 请求,这些服务已被限制并可能失败。如果您使用多个用户ID调用此API,该方法将尝试为每个用户ID发送此HTTP请求。然后将聚合任何错误消息,并将它们组合为以逗号分开列表。例如,如果此方法被调用五次 UserIds : {1, 2, 3, 4, 5} 并且对用户 2 和 4 的请求失败,那么以下错误消息将出现: HTTP failure for UserId 2: Timedout, HTTP 504 (Service unavailable) failure for UserId 4: Service exception. 该消息总是包含 failure for UserId {} 如果是 HTTP 错误。如果你传递了有效和无效的用户ID,那么这是不定义的行为,即一个 UserId 不是正数的值,因为一些网络请求可能在所有输入验证之前成功。

由于与禁止用户相关的风险,此方法只能在后端游戏服务器上调用。客户端调用将导致错误。您可以在工作室、团组队创作和团队测试中测试此 API,但禁令不适用于生产。此函数调用只会在生产游戏服务器上尝试禁止请求,而不是在工作室测试中。但是,所有输入验证步骤仍然会在 Studio 中工作。

此 API 使用了 用户限制开放云 API。你可以使用这些 API 来在第三方应用程序中管理你的禁令。

参数

config: Dictionary

<th>类型</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>用户ID</code></td>
<td>阵数组</td>
<td>用户ID必须强制进入体验(s)。最大尺寸为 <code>50</code>。</td>
</tr>
<tr>
<td><code>应用到宇宙</code></td>
<td>boolean 类型</td>
<td>将解除封禁传播到宇宙中的所有地方。</td>
</tr>
</tbody>
名称
默认值:""

返回

()

代码示例

The following un-bans a user, as well as another unrelated account with UserId 789.

Unbanning Users

local Players = game:GetService("Players")
if shouldBeUnbanned(player) then
local config: UnbanConfigType = {
UserIds = { player.UserId, 789 },
ApplyToUniverse = false,
}
local success, err = pcall(function()
return Players:UnbanAsync(config)
end)
print(success, err)
end

活动

PlayerAdded

当玩家进入游戏时,此事件发生。这用于在玩家加入游戏时发射事件,例如加载玩家保存的 GlobalDataStore 数据。

这可以与 Players.PlayerRemoving 事件一起使用,该事件会在玩家即将离开游戏时触发。例实例,如果你想每次新玩家加入或离开游戏时打印消息:


local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
print(player.Name .. " joined the game!")
end)
Players.PlayerRemoving:Connect(function(player)
print(player.Name .. " left the game!")
end)

如果您想跟踪玩家角色何时添加或从游戏中删除,例如当玩家重生或死亡时,您可以使用 Player.CharacterAddedPlayer.CharacterRemoving 函数。

请注意,此事件在 游戏 模式中不像期望的那样工作,因为玩家在运行脚本连接到 PlayerAdded 之前创建。为了处理这种情况以及玩家进入游戏后将脚本添加到游戏的情况,创建一个 onPlayerAdded() 函数,您可以调用以处理玩家的入口。

参数

player: Player

加入游戏的玩家实例。


代码示例

This example will print "A player has entered: " followed by the name of the player that enters/joins a game every time a player joins.

Players.PlayerAdded

local Players = game:GetService("Players")
local function onPlayerAdded(player)
print("A player has entered: " .. player.Name)
end
Players.PlayerAdded:Connect(onPlayerAdded)

PlayerMembershipChanged

当游戏服务器检测到玩家的会员资格已更改时,此事件会发生。请注意,服务器只会在“高级”模态关闭后尝试检查和更新会员 才会。因此,为了应对用户在游戏中购买高级 以外 的情况,你仍然需要提示他们购买高Premium;这将显示一个消息告诉他们他们已经升级了,一旦他们关闭模态,游戏服务器将更新他们的会员并触发此事件。

要了解更多关于如何将高级融入到您的体验中并通过基于交互的付款系统进行货币化,请参阅基于交互的付款

还见:

参数

player: Player

代码示例

The function in the code sample runs after the game server confirms a player's membership has changed. It demonstrates how you can grant players access to Premium benefits (or revoke them) when their membership status changes.

Handling Premium Membership Changes

local Players = game:GetService("Players")
local function grantPremiumBenefits(player)
-- Grant the player access to Premium-only areas, items, or anything you can imagine!
print("Giving", player, "premium benefits!")
end
local function playerAdded(player)
if player.MembershipType == Enum.MembershipType.Premium then
grantPremiumBenefits(player)
end
end
local function playerMembershipChanged(player)
print("Received event PlayerMembershipChanged. New membership = " .. tostring(player.MembershipType))
if player.MembershipType == Enum.MembershipType.Premium then
grantPremiumBenefits(player)
end
end
Players.PlayerAdded:Connect(playerAdded)
Players.PlayerMembershipChanged:Connect(playerMembershipChanged)

PlayerRemoving

玩家移除事件在 Player 离开游戏之前发生。此事件在 之前发生,行为与 相似。由于它在实际删除 Player 之前发射,因此使用 GlobalDataStore 存储玩家数据时,这个事件很有用。

这可以与 Player.PlayerAdded 事件一起使用,当玩家加入游戏时触发。例实例,每当新玩家加入或离开游戏时打印消息:


local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
print(player.Name .. " joined the game!")
end)
Players.PlayerRemoving:Connect(function(player)
print(player.Name .. " left the game!")
end)

如果您想跟踪玩家角色何时添加或从游戏中删除,例如当玩家重生或死亡时,您可以使用 Player.CharacterAddedPlayer.CharacterRemoving 函数。

参数

player: Player

离开游戏的玩家实例。


代码示例

This code will print "A player has left: ", followed by the player's name, every time a player leaves:

Players.PlayerRemoving

local Players = game:GetService("Players")
local function onPlayerRemoving(player)
print("A player has left: " .. player.Name)
end
Players.PlayerRemoving:Connect(onPlayerRemoving)

UserSubscriptionStatusChanged

当游戏服务器识别到用户的某个订阅状态已更改时,此事件会发生。请注意,服务器只会在订阅购买模态关闭后尝试检查和更新状态 。为了记录用户在游戏玩时购买订阅 的情况 ,你必须仍然提示他们购买订阅;提示会显示一个消息告诉用户他们已经订阅,然后关闭模态后,游戏服务器更新他们的订阅状态并触发此事件。

请注意,只有服务器脚本才能收到此事件。

参数

user: Player

订阅状态已更改的用户。

subscriptionId: string

状态更改的订阅ID。