Players 服务包含 Player 对象,用于当前连接的客户端到 Roblox 服务器。它还包含有关地场景的配置信息。它可以获取不连接到服务器的玩家,例如角色外观、朋友和头像缩略图。
概要
属性
启用或禁用三个 Players 方法 ( BanAsync() , UnbanAsync() 和 1> Class.Players:GetBanHistoryAsync()|GetBanHistoryAsync()1> ) 组成禁令 API。 此属性不是脚本可以在 Studio
指示是否启用泡泡聊天。它是通过 Players:SetChatStyle() 方法设置的。
指示 Class.Character|Characters 是否会自动重生。
指示是否启用经典聊天;由 Players:SetChatStyle() 方法设置。
Class.Player 是 LocalScript 的运行对象。
可以在服务器上的最大玩家数。
服务器上的玩家数量的预期数量。
控制玩家角色重生所需的时间。
方法
让本地玩家聊天显示给定的消信息。
返回所有连接的 Player 对象的表。
设置是否使用泡泡聊天和经典聊天,并告诉团队聊天和 Chat 做什么。
使 LocalPlayer 聊天给出的消信息,只有用户在同一团队中才能查看。
用户从您的体验中禁止,具有选项来指定持续时间,理由,是否适用于整个宇宙或仅适用当前位场景,以及更多。此方法通过 Players.BanningEnabled 属性,可以在 Studio 中切换。
- CreateHumanoidModelFromDescription(description : HumanoidDescription,rigType : Enum.HumanoidRigType,assetTypeVerification : Enum.AssetTypeVerification):Model
返回一个带有所有在人形描述中指定的角色模型,并且是按照 R6 或 R15 在装备类型上指定的。
返回一个带有所有装备的角色模型,用户指定的用户名与通过传送的角色模型匹配。
检索体验宇宙中的用户禁令和解除禁令历史。此方法通过 Players.BanningEnabled 属性,可以在 Studio 中切换。
返回给定用户的角色外观的信息。
返回一个 FriendPages 对象,其中包含所有给定玩家的朋友的信息。
为指定的服装返回人形描述,这将与服装的零件/颜色/动画等部分/颜色相配。
返回一个人形描述,该描述包括所有装备在用户指定的用户的头像。
向 Roblox 网站发送用户名为 UserId 的帐户的查询。
向 Roblox 网站发送查询,以便为指定用户名的帐户 userId。
- GetUserThumbnailAsync(userId : number,thumbnailType : Enum.ThumbnailType,thumbnailSize : Enum.ThumbnailSize):Tuple
返回玩家缩略图的内容 URL,根据大小和输入以及一个Boolean描述是否准备好使用图像。
使用 Players:BanAsync() 或 Players.BanningEnabled 来解除屏蔽玩家的禁云端 API。此方法通过 Class.Players.BanningEnabled 属性,可在 Studio 中切换。
活动
当玩家进入游戏时,发射。
当游戏服务器检测到玩家的会员更改时触发。
玩家将离开游戏时触发。
当游戏服务器检测到用户的某个订阅的状态已更改时,它会发生。
属性
BanningEnabled
启用或禁用三个 Players 方法 ( BanAsync() , UnbanAsync() 和 1> Class.Players:GetBanHistoryAsync()|GetBanHistoryAsync()1> ) 组成禁令 API。 此属性不是脚本可以在 Studio
BubbleChat
BubbleChat 属性表示是否启用泡泡聊天。它使用 Players:SetChatStyle() 方法使用 Enum.ChatStyle 枚。
当此聊天模式启用时,游戏会在屏幕左上角的聊天用户界面中显示聊天。
还有两个聊天模式,Players.ClassicChat和一个聊天模式,在 classic 和 bubble chat 都有启用。
CharacterAutoLoads
CharacterAutoLoad 属性表示 Class.Character|Characters 是否会自动重生。默认值是 true。
如果该属性已禁用 (假),玩家 Class.Character|Characters 将不会在玩家 Player:LoadCharacter() 调用每个 Player 时,包括玩家加入体验时。
这可能对于玩家有无限的生命的体验有用,例如在竞争游戏中,玩家不会重生直到游戏回合结束。
代码示例
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.
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 和一个聊天模式,在 котором both classic 和 bubble chat 都是启用的。
LocalPlayer
LocalPlayer 是一个只读的属性,它指向 Player 的客户端运行体验。
这个属性仅为 LocalScripts 和 ModuleScripts 所需,因为它们在客户端上运行。对于服务器,在哪个 Script 对象运行其代验证码,该属性是 1> nil1> 。
PreferredPlayers
PreferredPlayers 属性表示 Roblox 的匹配器将填充服务器的玩家数量。 此数量将小于体验支持的最大玩家数 ( Players.MaxPlayers )。
RespawnTime
RespawnTime 属性控制时间,它以秒为单位,表示玩家在 Players.CharacterAutoLoads 启用时需要重生的时间。默认为 5.0 秒。
这很有用,当你想要根据体验类型改变重生时间,但不想手动处理玩家。
虽然这个属性可以从 Script 中设置,但您可以在 Studio 的 Players 窗口中直接设置它。
UseStrafingAnimations
方法
Chat
此函数使本地玩家聊天显示指定的信息。 因为此项目受到保护,尝试在 Script 或 LocalScript 中使用它将导致错误。
相反,当创建自定义聊天系统或需要聊天访问的系统时,您可以使用 Chat 服务的 Chat:Chat() 函数。
参数
聊天信息。
返回
代码示例
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.
-- 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
此函数在 Players 中搜索每个 Player.UserId 在 1> Class.Players1> 中为一个拥有 4> Class.Player.UserId4> 的玩家搜索。如果该玩家不存在,它将返回 7>nil7> 。它与以下函数相等:
local Players = game:GetService("Players")
local function getPlayerByUserId(userId)
for _, player in Players:GetPlayers() do
if player.UserId == userId then
return player
end
end
end
此方法有助于使用 MarketplaceService.ProcessReceipt ,该方法提供包含购买者的用户ID 和不是引用 Player 对象自身的引用表。大多数游戏都会需要参考玩家才能授予产品。
参数
玩家的 Player.UserId 正在指定。
返回
代码示例
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:
- Sets up the ProcessReceipt callback function to handle the purchase of two developer products for an experience.
- Checks for and records purchases using a GlobalDataStore called PurchaseHistory.
- Properly returns PurchaseGranted if the transaction completes successfully, or if the function detects that the purchase has already been granted using the PurchaseHistory data store.
local MarketplaceService = game:GetService("MarketplaceService")
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
-- Data store setup for tracking purchases that were successfully processed
local purchaseHistoryStore = DataStoreService:GetDataStore("PurchaseHistory")
-- Table setup containing product IDs and functions for handling purchases
local productFunctions = {}
-- ProductId 123123 for a full heal
productFunctions[123123] = function(_receipt, player)
-- Logic for the player buying a full heal
if player.Character and player.Character:FindFirstChild("Humanoid") then
-- Heal the player to full health
player.Character.Humanoid.Health = player.Character.Humanoid.MaxHealth
-- Indicate a successful purchase
return true
end
end
-- ProductId 456456 for 100 gold
productFunctions[456456] = function(_receipt, player)
-- Logic for player buying 100 gold
local stats = player:FindFirstChild("leaderstats")
local gold = stats and stats:FindFirstChild("Gold")
if gold then
gold.Value = gold.Value + 100
-- Indicate a successful purchase
return true
end
end
-- The core 'ProcessReceipt' callback function
local function processReceipt(receiptInfo)
-- Check the data store to determine if the product was already granted
local playerProductKey = receiptInfo.PurchaseId
local purchased = false
local success, result, errorMessage
success, errorMessage = pcall(function()
purchased = purchaseHistoryStore:GetAsync(playerProductKey)
end)
-- If the purchase is recorded, the product was already granted
if success and purchased then
return Enum.ProductPurchaseDecision.PurchaseGranted
elseif not success then
error("Data store error:" .. errorMessage)
end
-- Update the purchase record
local success, isPurchaseRecorded = pcall(function()
return purchaseHistoryStore:UpdateAsync(playerProductKey, function(alreadyPurchased)
if alreadyPurchased then
return true
end
-- Find the player who made the purchase in the server
local player = Players:GetPlayerByUserId(receiptInfo.PlayerId)
if not player then
-- The player probably left the game
-- If the player returns, the callback is called again
return nil
end
local handler = productFunctions[receiptInfo.ProductId]
local success, result = pcall(handler, receiptInfo, player)
-- Do not record the purchase if granting the product failed
if not success or not result then
error("Failed to process a product purchase for ProductId: " .. tostring(receiptInfo.ProductId) .. " Player: " .. tostring(player) .. " Error: " .. tostring(result))
return nil
end
-- Record the transaction in purchaseHistoryStore
return true
end)
end)
if not success then
error("Failed to process receipt due to data store error.")
return Enum.ProductPurchaseDecision.NotProcessedYet
elseif isPurchaseRecorded == nil then
-- Did not update the value in the data store
return Enum.ProductPurchaseDecision.NotProcessedYet
else
-- IMPORTANT: Tell Roblox that the game successfully handled the purchase
return Enum.ProductPurchaseDecision.PurchaseGranted
end
end
-- Set the callback; this can only be done once by one script on the server!
MarketplaceService.ProcessReceipt = processReceipt
GetPlayerFromCharacter
此函数将返回与指定的 Player 相关的,或 Player.Character 如果无法找到。它与以下函数相同:
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)访问权限。 该函数的反向可以描述为获得玩家角色。 要实现此操作,请访问角色属性。
参数
一个角色实例,您想要从。
返回
代码示例
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
此方法将返回所有现有连接的 Player 对象的表。它的工作方式与 Instance:GetChildren() 类似,除了它只会返回在 Player 下找到的对象。 使用 2>for2> 循环时,它是有用的 для在游戏中遍历所有玩家。
local Players = game:GetService("Players")for _, player in Players:GetPlayers() doprint(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)
返回
包含服务器中所有玩家的表。
代码示例
This code sample listens for players spawning and gives them Sparkles in their head. It does this by defining two functions, onPlayerSpawned and onPlayerAdded.
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 ,并告诉 TeamChat 和聊天何时使用 Enum.ChatStyle 枚。 因此该项目受到保护,尝试在 Script 或 LocalScript 中使用它将导致错误。
当聊天模式由游戏设置时,该函数内部使用。
参数
指定的聊天风格已设置。
返回
代码示例
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.
-- 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 聊天给予的消信息,只有在同一团队的用户才能查看。因为此项目受到保护,尝试在 Script 或 LocalScript 中使用它会导致错误。
当 Players.LocalPlayer 向他们的团队发送消息时,该函数内部使用。
参数
正在聊天。
返回
代码示例
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.
-- 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
Class.Players:BanAsync() 方法允许您轻松禁止违反您的体验指南的用户。您可以指定禁令持续时间、启用禁令传播到可疑帐户,并为禁令用户提供消息按照使用规则。您还可以在体验规则的任何位
禁止和消息
受到禁令的用户将被立即驱逐并防止他们重新加入您的体验。他们将被提供一个错误模态,显示他们的禁令时间剩余和您的 DisplayReason 。 Roblox 的后端过滤器统可以驱逐玩家在您指定的所有服务器从所指定的场景方(s)。
地方和宇宙
默认情况下,封禁将扩展到该宇宙内的任何地方。 要将封禁仅限于该 API 调用的地方,请配置 ApplyToUniverse 为 false 。 但如果用户在宇宙开始地点被封禁,它将导致用户被排除出整个宇宙,无论是否启用全宇宙封禁。
替换帐户
用户常常在多个不同的帐户下玩,这些帐户通常被称为替换帐户或 alt 帐户,它们有时用于来回避帐户禁令。要帮助您保持禁令用户出,这个 API 的默认行为将从源帐户您禁止的所有禁令传播到其所有的潜在 alt 帐户。您可以通过配置 ExcludeAltAccounts 来关闭禁令传播到 alt 帐
封禁时间
不是所有违规都一样,所以不是所有的禁令都
错误和节流阀
此方法调用 HTTP 调用端到端服务,受到限制并可能失败。 如果您使用此 API 与多于一个 UserId 调用此 API,此方法将尝试为每个 ID 创建 HTTP 请求。然后,如果此方法被调用五个用户并要求它们的 Class.Player.UserId|
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 来管理您在第三方应用程序中的禁令。
参数
UserIds (必须; 阵数组) — 玩家禁止列的UserIds 的阵列。最大大小为50。
ApplyToUniverse (可选) — 是否将禁令传播到体验宇宙内的所有地方。默认值是 true。
Duration (需要; 整数) — 封封停的持续时间,在秒。永久封禁应该有一个值为 -1 的。 0 和所有其他负面值都无效。
DisplayReason (需要; 字符串) — 用户尝试加入体验时会显示的消息。最大字符串长度为 400 。
PrivateReason (需要; 字符串) — 内部消息,查询用户的禁令记录时将返回。最大字符串长度为 1000 。
ExcludeAltAccounts (可选) — 当 true 时,Roblox 不会尝试禁止 alt 帐户。默认值是 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.
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
返回一个带有所有在人形描述中指定的角色模型,并且是按照 R6 或 R15 在装备类型上指定的。
参数
指定返回角色的外观。
指定返回角色将是 R6 或 R15。
资产类型验证是否会加载模型(您应该将其设置为“总是”,除非您想要加载非目录资产)。
返回
一个人形角色模型。
代码示例
This code sample creates a Humanoid Model from the passed in HumanoidDescription and parents the Model to the Workspace.
game.Players:CreateHumanoidModelFromDescription(Instance.new("HumanoidDescription"), Enum.HumanoidRigType.R15).Parent = game.Workspace
CreateHumanoidModelFromUserId
返回一个带有该用户指定的虚拟形象的所有装备的角色模型。这包括该角色是否当前为 R6 或 R15。
参数
Roblox用户的用户ID。(UserId是用户的个人资料中的数字,例如www.roblox.com/用户/1/个人资料)。
返回
一个人形角色模型。
代码示例
This code sample creates a Humanoid Model to match the avatar of the passed in User ID, and parents the Model to the Workspace.
game.Players:CreateHumanoidModelFromUserId(1).Parent = game.Workspace
GetBanHistoryAsync
检索体验宇宙中的任何用户的禁令和解除禁令历史。此方法将返回一个 BanHistoryPages 实例,其继承自 Pages。此方法通过 Players.BanningEnabled 属性, которое您可以在 Studio 中切换。
此功能调用仅在生产游戏服务器上成功,不会在客户端设备或 Studio 中执行。
此 API 使用 用户限制开放云 API。您将能够使用这些 API 来管理您在第三方应用程序中的禁令。
参数
返回
请参阅BanHistoryPages以获取返回引用。
GetCharacterAppearanceInfoAsync
此函数在 Roblox 网站上的商品(无视装备)的形式为字典。它不是要与 GetCharacterAppearanceAsync ,其实际加载描述此方法的资产。您可以使用 InsertService:LoadAsset() 来加载使用此玩家法描述的资产。结构如
<tr><td><code>资产</code></td><td>表 (见下表)</td><td>描述已装备的资产(帽子、身体部件等)</td></tr><tr><td><code>身体颜色</code></td><td>表 (见下表)</td><td>为每个腿部描述 BrickColor 值</td></tr><tr><td><code>bodyColor3s)</code></td><td>表 (见下表)</td><td>为每个可能与身体颜色不完全匹配的腿部描述颜色3 实例</td></tr><tr><td><code>默认裤子已应用</code></td><td>boolean</td><td>描述是否应用默认裤子</td></tr><tr><td><code>默认衬衫已应用</code></td><td>boolean</td><td>描述是否应用默认上衣</td></tr><tr><td><code>表情符号</code></td><td>表 (见下表)</td><td>描述已装备的表情动画</td></tr><tr><td><code>playerAvatarType</code></td><td>字符串</td><td>R15 或 R6</td></tr><tr><td><code>缩放</code></td><td>表 (见下表)</td><td>描述各种身体缩放因素</td></tr>
名称 | 类型 | 描述 |
---|
资产子表
资产 表是一个包含以下键描述玩家当前装备的资产的表阵列:
<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,1> head1>,4> height4>,7> proportion7>,9> depth9>,scales
身体颜色子表
bodyColors 表有以下钥匙,每个钥匙都对应一个 BrickColor ID 号,可以用 BrickColor.new(id) :
参数
指定玩家的 * 用户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?
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 函数返回一个 FriendPages 对象,该对象包含所有给定用户的朋友的信息。 内容在 FriendPages 对象内的表中,其中的字段为:
<tr><td>身份证</td><td>int64</td><td>朋好友的用户ID</td></tr><tr><td>用户名</td><td>字符串</td><td>朋好友的用户名</td></tr><tr><td>显示名称</td><td>字符串</td><td>Class.Player.DisplayName|显示名称 的朋好友。</td></tr>
名称 | 类型 | 描述 |
---|
查看代码示例,这是一个简单的方法来遍历所有玩家的朋友。
参数
玩家的用户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.
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返回人形描述,这将与服装的零件/颜色/动画等部分设置。 服装可以是用户创建的,或者是Roblox创建的服装束的服装。
参数
人形描述的服装的 id。
返回
人形描述用传统服装Id通过的规格初始化。
代码示例
Shows how to get the HumanoidDescription for bundle 799 (Fishman).
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
返回一个人形描述,该描述所装备的一切都在指定的用户ID 下指定。包括鳞片和身体颜色。
参数
Roblox用户的用户ID。(UserId是用户的个人资料中的数字,例如www.roblox.com/用户/1/个人资料)。
返回
人形描述用户在头像规格中传入的内容。
代码示例
This code sample shows how to use GetHumanoidDescriptionFromUserId() to create a Humanoid Model.
game.Players:CreateHumanoidModelFromDescription(game.Players:GetHumanoidDescriptionFromUserId(1), Enum.HumanoidRigType.R15).Parent = game.Workspace
GetNameFromUserIdAsync
获取名称从 UserIdAsync 函数将向 Roblox 网站发送一个查询,要求用户名是指定的 UserId 。
此方法会发生错误,如果没有与指定的用户ID 创建帐户。 如果您不确定此帐户是否存在,请使用 pcall 包装调用此函数。 此外,您可以手动缓存结果以便以同一的用户ID 快速调用未来的调用。请参阅代码示例学习更多。
参数
玩家的 Player.UserId 正在指定。
返回
具有指定 Player.UserId 的用户的名称。
代码示例
This code sample demonstrates using the Players:GetNameFromUserIdAsync() method to get a user's Player.Name from their Player.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.
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 包围调用。此外,您可以手动缓存结果以便以后使用相同的用户名快速调用。请参阅代码示例学习更多。
参数
指定玩家的用户名。
返回
用户的 Player.UserId 的。
代码示例
This code sample demonstrates using the Players:GetUserIdFromNameAsync() method to get a user's Player.UserId from their Player.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.
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.Image 或 Decal.Texture 用于显示用户虚拟形象图像在体验中。
参数
返回
包含用户缩略图内容URL的表示,以及描述图像是否准备好使用或不是的Boolean。
代码示例
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().
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 设置的封禁。在其他 words,宇宙级别的取消封封停不会无
此方法调用 HTTP 调用将端后服务,这些服务受到限制并可能失败。 如果您使用多个 UserId 调用此 API ,此方法将尝试为每个 UserId 创建此 HTTP 调用。 它将
由于禁止用户所带来的风险,因此此方法仅能在后端游戏服务器上调用。客户端调用将导致错误。您可以在 Studio、团组队创作和团队测试中测试此 API,但禁止不适用于生产。此函数调用只会尝试在生产游戏服务器上尝试禁止请求,而不是在 Studio 测试。
此 API 使用 用户限制开放云 API。您将能够使用这些 API 来管理您在第三方应用程序中的禁令。
参数
<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.
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
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.CharacterAdded 和 Player.CharacterRemoving 函数。
注意,该事件在 播放 模式中不如期待地工作,因为玩家在 PlayerAdded 之前创建。 要处理此情况,请在脚本在游戏中添加后,以及在玩家进入游戏后的情况下创建一个 onPlayerAdded() 函数,您可以调用它来处理玩家的入口。
参数
加入游戏的玩家的实例。
代码示例
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.
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print("A player has entered: " .. player.Name)
end
Players.PlayerAdded:Connect(onPlayerAdded)
PlayerMembershipChanged
当游戏服务器认为玩家的会员资格已更改时,该事件将发生。请注意,服务器只会在关闭 Premium 模态后尝试检查和更新会员资格 后 关闭 Premium 模式玩用。因此,要计算玩家在游戏中购买 Premium 的情况下,您必须仍然提示他们购买 Prem
要了解更多关于将 Premium 集成到您的体验并使用基于交互的付款系统进行货币化,请参阅基于交互的付款系统。
还请参阅:
- MarketplaceService:PromptPremiumPurchase(),用于提示用户购买高级
- MarketplaceService.PromptPremiumPurchaseFinished,发生在 Premium 购买界面关闭时触发
参数
代码示例
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.
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离开游戏之前发生。 此事件在ChildRemoved在游戏上,并且与Players相似。 因为它发生在1>
这可以与 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.CharacterAdded 和 Player.CharacterRemoving 函数。
参数
离开游戏的玩家的实例。
代码示例
This code will print "A player has left: ", followed by the player's name, every time a player leaves:
local Players = game:GetService("Players")
local function onPlayerRemoving(player)
print("A player has left: " .. player.Name)
end
Players.PlayerRemoving:Connect(onPlayerRemoving)