服務包含目前連接到 Roblox 伺服器的客戶端的對象。它也包含關於空間方配置的資訊。它可以擷取不連接到伺服器的玩家資訊,例如角色外觀、朋友和頭像縮圖。
概要
屬性
啟用或禁用組成禁止 API 的三種 Players 方法 ( BanAsync() , UnbanAsync() , 和 GetBanHistoryAsync() )此屬性無法腳本化,只能在工作室中修改。
指示是否啟用對話泡泡。它使用 Players:SetChatStyle() 方法設置。
指示 characters 是否會自動重生。
指示是否啟用經典聊天;由 Players:SetChatStyle() 方法設置。
在 Player 上運行的 LocalScript 。
伺服器中最多可以存在的玩家數量。
服務伺服器的首選玩家數量。
控制玩家角色重生所需的時間量。
方法
讓本地玩家聊天給定的訊息。
返回具有 Player 匹配給定實個體、實例的 Player.Character 或 nil 如果找不到一個,否則將返回空白。
返回所有現時連接的 Player 對象的表。
設置是否使用 BubbleChat 和 ClassicChat,並告知團隊聊天和 Chat 做什麼。
讓本地玩家聊天給出的訊息,只有相同團隊的使用者才能查看。
禁止使用者進入你的體驗,並提供選項來指定持續時間、原因、是否適用於整個宇宙或只有當前空間等等。這個方法由 Players.BanningEnabled 屬性啟用和禁用,您可以在 Studio 中切換。
- CreateHumanoidModelFromDescription(description : HumanoidDescription,rigType : Enum.HumanoidRigType,assetTypeVerification : Enum.AssetTypeVerification):Model
返回裝備了所有在 HumanoidDescription 中指定的內容的角色模型,並且是由 rigType 指定的 R6 或 R15。
返回裝備配備完整的角色模型設置,與傳送的使用者ID指定的使用者的虛擬形象匹配。
取得體驗宇宙內任何使用者的禁令和解除禁令歷史記錄。這個方法由 Players.BanningEnabled 屬性啟用和禁用,您可以在 Studio 中切換。
返回給定用戶的角色外觀資訊。
返回包含所有指定玩家朋友資訊的 FriendPages 對象。
返回指定服裝的 HumanoidDescription,該服裝將使用其零件/顏色/動畫等設置。
返回一個人形描述,指定用於使用傳入的 userId指定用戶的虛擬人偶所裝備的一切。
向 Roblox 網站發送查詢,以指定的 UserId 帳戶名稱的帳戶用戶名。
向 Roblox 網站發送查詢,以獲得指定使用者名稱的帳戶的 userId 資訊。
- GetUserThumbnailAsync(userId : number,thumbnailType : Enum.ThumbnailType,thumbnailSize : Enum.ThumbnailSize):Tuple
返回玩家縮略圖的內容 URL,給出尺寸和輸入,以及描述是否準備好使用圖像的 boolean 值。
取消禁止玩家從 Players:BanAsync() 或使用者限制開放雲端 API 被禁止的資格。這個方法由 Players.BanningEnabled 屬性啟用和禁用,您可以在 Studio 中切換。
活動
當玩家進入遊戲時發生火災。
當遊戲伺服器認為玩家的會員資格已變更時,發生火災。
當玩家即將離開遊戲時發生火災。
當遊戲伺服器認為用戶的某個訂閱狀態已變更時,發生火災。
屬性
BanningEnabled
啟用或禁用組成禁止 API 的三種 Players 方法 ( BanAsync() , UnbanAsync() , 和 GetBanHistoryAsync() )此屬性無法腳本化,只能在工作室中修改。
BubbleChat
此屬性指示是否啟用對話泡泡。它使用 Players:SetChatStyle() 枚列設置,使用 Enum.ChatStyle 方法設置。
啟用此聊天模式時,遊戲會在屏幕左上角顯示聊天用戶介面。
還有兩種聊天模式,Players.ClassicChat 和啟用了 classic 和 bubble 聊天的聊天模式。
CharacterAutoLoads
此屬性表示 characters 是否會自動重生。默認值為真。
如果此屬性被禁用(false),玩家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 和啟用了 classic 和 bubble 聊天的聊天模式。
LocalPlayer
這個只讀屬性指的是 Player 的客戶端運行體驗。
此屬性只適用於 LocalScripts 和 ModuleScripts 由他們需要的,因為它們在客戶端運行。對於服務伺服器,在哪裡Script物件運行其代碼,此屬性是nil。
RespawnTime
此屬性控制玩家在 Players.CharacterAutoLoads 時重生所需的時間,以秒為單位。默認值為 5.0 秒。
當您想要根據體驗類型變更重生所需時間,但不想單獨處理重生玩家時,這很有用。
雖然此屬性可以從 內設置,但您可以更容易直接在 Studio 的 Explorer 窗口中設置它。
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
此功能會搜尋每個 在 中找到一個與給定的使用者ID匹配的人。如果此玩家不存在,它只會返回 nil 。它相當於以下功能:
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.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 ,或 nil 如果找不到一個,否則返回空白。它相當於以下功能:
local function getPlayerFromCharacter(character)
for _, player in game:GetService("Players"):GetPlayers() do
if player.Character == character then
return player
end
end
end
此方法通常在玩家角色中發生某些事件時使用(例如他們的 Class.Humanoid``Class.Humanoid.Died|dying)。這種事件可能不會直接引用玩家對物件,但這個方法提供了容易的訪使用權 通行權 存取。這個函數的逆向可以描述為獲得玩家的角色。若要執行此操作,請單純存取角色屬性。
參數
你想從中獲得玩家的角色實例。
返回
範例程式碼
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 在 Players 下找到的對象。當與 for 循環一起使用時,它對於在遊戲中循環所有玩家很有用。
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,並告知團隊聊天和聊天使用 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
方法允許您輕鬆禁止違反體驗指南的用戶。您可以指定禁令期限,啟用禁令傳播到懷疑的替代帳戶,並向被禁止的使用者提供遵照 使用指南 的訊息。你也應該在所有使用者都能訪問的地方發布你的經驗規則,並提供一個方法讓他們提出上訴。這個方法由 Players.BanningEnabled 屬性啟用和禁用,您可以在 Studio 中切換。
禁止和訊息傳送
被禁止的使用者將立即驅逐並防止重新加入您的體驗。他們將被提供一個錯誤模式,顯示他們禁令的剩餘時間和您的 DisplayReason 。Roblox 的後端系統會從您指定的所有伺服器中驅逐玩家到指定的空間(s)。DisplayReason 最長可達 400 個字元,並受到文字過篩選器。有關接受的模態文字的更多資訊,請參閱禁止傳送訊息。
地點和宇宙
預設情況下,禁令擴展到宇宙內的任何地方。要限制禁令只針對從這個 API 被呼叫的地方,配置 ApplyToUniverse 到 false 。然而,如果使用者在宇宙的起點被禁止,它會導致使用者被排除出宇宙的全部,無論是否有通用禁令存在。
替代帳戶
使用者經常在多個不同帳戶下進行遊戲,也稱為替代帳戶或 alt 帳戶,有時會用於繞過帳戶封鎖。為了幫助您保持已被禁止的用戶出入,此 API 的預設行為將將所有禁令從您被禁止的來源帳戶傳播到任何可疑的替代帳戶。您可以通過配置 ExcludeAltAccounts 到 true 來關閉禁令傳播到替代帳戶。
禁止期限
不是所有的侵權行為都一樣,因此不是所有的禁令應該一樣長。這個 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 來管理第三方應用程式中的禁令。
參數
UserIds (必須;阵陣列)—禁止的玩家數量為 UserIds 。最大尺寸為 50 。
ApplyToUniverse (可選;是否) — 是否禁止傳播到體驗宇宙內的所有地方。默認值為 true 。
Duration (必須;整數)—停權令時間,以秒為單位。永久封鎖應具有值 -1 。0和所有其他負值無效。
DisplayReason (必須;字串)—當使用者嘗試加入體驗並失敗時,將顯示給使用者的訊息。最大字串長度是 400 。
PrivateReason (必須;字串)—當查詢用戶的禁令歷史時返回的內部消息。最大字串長度是 1000 。
ExcludeAltAccounts (可選;是否)—當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.
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。
參數
指定返回的字元外觀。
指定返回的字符是否為 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
返回裝備配備完整的角色模型設置,與傳送的使用者ID指定的使用者的虛擬形象匹配。這包括該角色目前是否為 R6 或 R15。
參數
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.
game.Players:CreateHumanoidModelFromUserId(1).Parent = game.Workspace
GetBanHistoryAsync
取得體驗宇宙內任何使用者的禁令和解除禁令歷史記錄。此方法返回一個從 BanHistoryPages 傳承的 Pages 實例。這個方法由 Players.BanningEnabled 屬性啟用和禁用,您可以在 Studio 中切換。
此功能呼叫只會在生產遊戲伺服器上成功,而不會在客戶端裝置或 Studio 中。
此 API 使用 使用者限制開放雲端 API。您可以使用這些 API 來管理第三方應用程式中的禁令。
參數
返回
參見 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>bodyColor3s</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,可以與BrickColor.new(id)結合:leftArmColorId、torsoColorId、rightArmColorId、headColorId、leftLegColorId、rightLegColorId。
參數
指定玩家的* uid。
返回
包含給定使用者角色外觀資訊的辭典。
範例程式碼
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 物件內的項目是擁有以下欄位的表:
<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>
名稱 |
---|
查看代碼樣本以獲得一種簡單的方法來循環所有玩家的朋友。
參數
指定玩家的使用者 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 創建的包裝的服裝。
參數
尋找 HumanoidDescription 的服裝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
返回一個人形描述,指定用於使用傳入的 userId指定用戶的虛擬人偶所裝備的一切。也包括尺寸和身體顏色。
參數
Roblox 使用者的使用者 ID。(使用者 ID 是使用者個人檔案的數字,例如 www.roblox.com/users/1/profile)。
返回
使用傳入使用者的虛擬人偶規格初始化的人形描述。
範例程式碼
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
GetNameFromUserIdAsync Players 功能將向 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
此功能返回玩家的虛擬人偶給予的UserId圖像的內容URL,作為Enum.ThumbnailSize枚列的所需圖像尺寸,以及作為Enum.ThumbnailType枚列的所需類型。它還返回一個描述圖像是否準備好使用的 boolean 值。
最常見的情況下,此方法會與 ImageLabel.Image 或 Decal.Texture 一起使用,以在體驗中顯示使用者頭像圖像。
參數
返回
包含指定參數的使用者縮略圖內容 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().
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 不是正數,因為一些網絡請求可能在所有輸入驗證之前成功。
由於禁止使用者所帶來的風險,此方法只能在後端遊戲伺服器上呼叫。客戶端呼叫將導致發生錯誤。您可以在 Studio、團隊創作和團隊測試中測試此 API,但禁令不適用於生產。此功能呼叫只會在生產遊戲伺服器上嘗試禁止請求,而不是在 Studio 測試中。但是,所有輸入驗證步驟仍然會在 Studio 中工作。
此 API 使用 使用者限制開放雲端 API。您可以使用這些 API 來管理第三方應用程式中的禁令。
參數
<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.
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.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;這將顯示一個訊息告訴他們他們已升級,一旦他們關閉模組,遊戲伺服器將更新他們的會員資格並觸發此事件。
若要進一步了解並將高級融入到您的體驗中,並使用基於參與度的付款系統來盈利,請參閱參與度付款。
也見:
- MarketplaceService:PromptPremiumPurchase() , 用於提示用戶購買高Premium
- 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 上的行為與 Instance.DescendantRemoving 相似。由於在實際移除 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.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)