Players
The Players service contains Player objects for presently connected clients to a Roblox server. It also contains information about a place's configuration. It can fetch information about players not connected to the server, such as character appearances, friends, and avatar thumbnail.
Summary
Properties
Indicates whether or not bubble chat is enabled. It is set with the Players:SetChatStyle() method.
Indicates whether Class.Character|Characters will respawn automatically.
Indicates whether or not classic chat is enabled; set by the Players:SetChatStyle() method.
The Player that the LocalScript is running for.
The maximum number of players that can be in a server.
The preferred number of players for a server.
Controls the amount of time taken for a players character to respawn.
Methods
Makes the local player chat the given message.
Returns the Player with the given UserId if they are in-game.
Returns the Player whose Character matches the given instance, or nil if one cannot be found.
Returns a table of all presently connected Player objects.
Sets whether BubbleChat and ClassicChat are being used, and tells TeamChat and Chat what to do.
Makes the LocalPlayer chat the given message, which will only be viewable by users on the same team.
Bans users from your experience, with options to specify duration, reason, whether the ban applies to the entire universe or just the current place, and more.
- CreateHumanoidModelFromDescription(description : HumanoidDescription,rigType : Enum.HumanoidRigType,assetTypeVerification : Enum.AssetTypeVerification):Model
Returns a character Model equipped with everything specified in the passed in HumanoidDescription, and is R6 or R15 as specified by the rigType.
Returns a character Model set-up with everything equipped to match the avatar of the user specified by the passed in userId.
Retrieves the ban and unban history of any user within the experience's universe.'
Returns information about the character appearance of a given user.
Returns a FriendPages object which contains information for all of the given player's friends.
Returns the HumanoidDescription for a specified outfit, which will be set with the parts/colors/Animations etc of the outfit.
Returns a HumanoidDescription which specifies everything equipped for the avatar of the user specified by the passed in userId.
Sends a query to the Roblox website for the username of an account with a given UserId.
Sends a query to the Roblox website for the userId of an account with a given username.
- GetUserThumbnailAsync(userId : number,thumbnailType : Enum.ThumbnailType,thumbnailSize : Enum.ThumbnailSize):Tuple
Returns the content URL of a player thumbnail given the size and type, as well as a boolean describing if the image is ready to use.
Unbans players banned from Players:BanAsync() or the User Restrictions Open Cloud API.
Events
Fires when a player enters the game.
Fires when the game server recognizes that a player's membership has changed.
Fires when a player is about to leave the game.
Fires when the game server recognizes that the user's status for a certain subscription has changed.
Properties
BubbleChat
The BubbleChat property indicates whether or not bubble chat is enabled. It is set with the Players:SetChatStyle() method using the Enum.ChatStyle enum.
When this chat mode is enabled, the game displays chats in the chat user interface at the top-left corner of the screen.
There are two other chat modes, Players.ClassicChat and a chat mode where both classic and bubble chat are enabled.
CharacterAutoLoads
The CharacterAutoLoads property indicates whether Class.Character|Characters will respawn automatically. The default value is true.
If this property is disabled (false), player Class.Character|Characters will not spawn until the Player:LoadCharacter() function is called for each Player, including when players join the experience.
This can be useful in experiences where players have finite lives, such as competitive games in which players do not respawn until a game round ends.
Code Samples
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
Indicates whether or not classic chat is enabled. This property is set by the Players:SetChatStyle() method using the Enum.ChatStyle enum.
When this chat mode is enabled, the game displays chats in a bubble above the sender's head.
There are two other chat modes, Players.BubbleChat and a chat mode where both classic and bubble chat are enabled.
LocalPlayer
LocalPlayer is a read-only property which refers to the Player whose client is running the experience.
This property is only defined for LocalScripts and ModuleScripts required by them, since they run on the client. For the server, on which Script objects run their code, this property is nil.
MaxPlayers
The MaxPlayers property determines the maximum number of players that can be in a server. This property can only be set through a specific place's settings on the Creator Dashboard or through Game Settings.
PreferredPlayers
The PreferredPlayers property indicates the number of players to which Roblox's matchmaker will fill servers. This number will be less than the maximum number of players (Players.MaxPlayers) supported by the experience.
RespawnTime
The RespawnTime property controls the time, in seconds, it takes for a player to respawn when Players.CharacterAutoLoads is true. It defaults to 5.0 seconds.
This is useful when you want to change how long it takes to respawn based on the type of your experience but don't want to handle spawning players individually.
Although this property can be set from within a Script, you can more easily set it directly on the Players object in Studio's Explorer window.
UseStrafingAnimations
Methods
Chat
This function makes the local player chat the given message. Since this item is protected, attempting to use it in a Script or LocalScript will cause an error.
Instead, when creating a custom chat system, or a system that needs access to the chat, you can use the Chat service's Chat:Chat() function instead.
Parameters
The message chatted.
Returns
Code Samples
-- 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
This function searches each player in Players for one whose Player.UserId matches the given UserId. If such a player does not exist, it simply returns nil. It is equivalent to the following function:
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
This method is useful in finding the purchaser of a developer product using MarketplaceService.ProcessReceipt, which provides a table that includes the purchaser's UserId and not a reference to the Player object itself. Most games will require a reference to the player in order to grant products.
Parameters
The Player.UserId of the player being specified.
Returns
Code Samples
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
local MarketplaceService = game:GetService("MarketplaceService")
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
-- Data store 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/code for player buying a full heal (may vary)
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/code for player buying 100 gold (may vary)
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)
-- Determine if the product was already granted by checking the data store
local playerProductKey = receiptInfo.PlayerId .. "_" .. receiptInfo.PurchaseId
local purchased = false
local success, result, errorMessage
success, errorMessage = pcall(function()
purchased = purchaseHistoryStore:GetAsync(playerProductKey)
end)
-- If purchase was 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
-- Determine if the product was already granted by checking the data store
local playerProductKey = receiptInfo.PlayerId .. "_" .. receiptInfo.PurchaseId
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 they come back, the callback will be called again
return nil
end
local handler = productFunctions[receiptInfo.ProductId]
local success, result = pcall(handler, receiptInfo, player)
-- If granting the product failed, do NOT record the purchase in datastores.
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
-- Didn't update the value in 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
This function returns the Player associated with the given Player.Character, or nil if one cannot be found. It is equivalent to the following function:
local function getPlayerFromCharacter(character)
for _, player in game:GetService("Players"):GetPlayers() do
if player.Character == character then
return player
end
end
end
This method is often used when some event in player's character fires (such as their Humanoid dying). Such an event might not directly reference the Player object, but this method provides easy access. The inverse of this function can be described as getting the Character of a Player. To do this, simply access the Character property.
Parameters
A character instance that you want to get the player from.
Returns
Code Samples
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
This method returns a table of all presently connected Player objects. It functions the same way Instance:GetChildren() would except that it only returns Player objects found under Players. When used with a for loop, it is useful for iterating over all players in a game.
local Players = game:GetService("Players")for _, player in Players:GetPlayers() doprint(player.Name)end
Scripts that connect to Players.PlayerAdded are often trying to process every Player that connects to the game. This method is useful for iterating over already-connected players that wouldn't fire PlayerAdded. Using this method ensures that no player is missed!
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)
Returns
A table containing all the players in the server.
Code Samples
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
This function sets whether BubbleChat and ClassicChat are being used, and tells TeamChat and Chat what to do using the Enum.ChatStyle enum. Since this item is protected, attempting to use it in a Script or LocalScript will cause an error.
This function is used internally when the chat mode is set by the game.
Parameters
The specified chat style being set.
Returns
Code Samples
-- 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
This function makes the Players.LocalPlayer chat the given message, which will only be viewable by users on the same team. Since this item is protected, attempting to use it in a Script or LocalScript will cause an error.
This function is used internally when the Players.LocalPlayer sends a message to their team.
Parameters
The message being chatted.
Returns
Code Samples
-- 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
The Players:BanAsync() method allows you to easily ban users who violate your experience's guidelines. You can specify the ban duration, enable the ban to propagate to suspected alternate accounts, and provide a message to the banned user in accordance with the Usage Guidelines. You should also post your experience rules somewhere accessible to all users and provide a way for them to appeal.
Banning and Messaging
Banned users will be immediately evicted and prevented from rejoining your experiences. They will be presented with an error modal displaying the time left on their ban and your DisplayReason. Roblox's backend systems will evict players across all servers from the place(s) that you specify. DisplayReason can have a maximum length of 400 characters and is subject to a text filter. For more information on acceptable modal text, see ban messaging.
Places and Universe
By default, bans extend to any place within that universe. To limit the ban to only the place from which this API is called, configure ApplyToUniverse to false. However, if a user is banned in the start place of the universe, it effectively results in the user being excluded from the entirety of the universe, irrespective of whether a universal ban is in place or not.
Alternative Accounts
Users often play under multiple different accounts, known as alternate accounts or alt accounts, which are sometimes used to circumvent account bans. To help you keep banned users out, the default behavior of this API will propagate all bans from the source account you banned to any of their suspected alt accounts. You can turn off ban propagations to alt accounts by configuring ExcludeAltAccounts to true.
Ban Duration
Not all transgressions are the same, so not all bans should be the same length. This API lets you configure the duration of the ban, in seconds, with the Duration field. To specify a permanent ban, set the field to -1. You may also want to dynamically configure the ban duration based on the user's ban history, which you can query for using Players:GetBanHistoryAsync(). For example, you may want to consider the number of bans, the duration of previous bans, or build logic off of the notes you save under PrivateReason which can be up to 1000 characters and are not text filtered. PrivateReason notes are never shared with the client and can be considered safe from attackers.
Errors and Throttling
This method invokes an HTTP call to backend services which are subject to throttling and may fail. If you're calling this API with more than one UserId, this method will attempt to make the HTTP call for each ID. It will then aggregate any error messages and join them as a comma separated list. For example, if this method is invoked for five users and requests for those with UserIds 2 and 4 fail, the following error message appears:
HTTP failure for UserId 2: Timedout, HTTP 504 (Service unavailable) failure for UserId 4: Service exception
The message will always include failure for UserId {} if it is an HTTP error.
Client-Side Requirement
Because of the risks associated with banning users, this method may only be called on the backend experience server (client-side calls will result in an error). You may test this API in Studio, during collaborative creation, or in a team test, but the bans will not apply to production.
This API uses the User Restrictions Open Cloud API. You will be able to utilize these APIs to manage your bans in third party applications.
Parameters
UserIds (required; array) — Array of UserIds of players to be banned. Max size is 50.
ApplyToUniverse (optional; boolean) — Whether ban propagates to all places within the experience universe. Default is true.
Duration (required; integer) — Duration of the ban, in seconds. Permanent bans should have a value of -1. 0 and all other negative values are invalid.
DisplayReason (required; string) — The message that will be displayed to users when they attempt to and fail to join an experience. Maximum string length is 400.
PrivateReason (required; string) — Internal messaging that will be returned when querying the user's ban history. Maximum string length is 1000.
ExcludeAltAccounts (optional; boolean) — When true, Roblox does not attempt to ban alt accounts. Default is false.
Returns
Code Samples
local Players = game:GetService("Players")
if shouldBeBanned(player: 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
Returns a character Model equipped with everything specified in the passed in HumanoidDescription, and is R6 or R15 as specified by the rigType.
Parameters
Specifies the appearance of the returned character.
Specifies whether the returned character will be R6 or R15.
Asset type verification determines if this function will load models or not (You should set this to Always unless you want to load non-catalog assets).
Returns
A Humanoid character Model.
Code Samples
game.Players:CreateHumanoidModelFromDescription(Instance.new("HumanoidDescription"), Enum.HumanoidRigType.R15).Parent = game.Workspace
CreateHumanoidModelFromUserId
Returns a character Model set-up with everything equipped to match the avatar of the user specified by the passed in userId. This includes whether that character is currently R6 or R15.
Parameters
The userId for a Roblox user. (The UserId is the number in the profile of the user e.g www.roblox.com/users/1/profile).
Returns
A Humanoid character Model.
Code Samples
game.Players:CreateHumanoidModelFromUserId(1).Parent = game.Workspace
GetBanHistoryAsync
Retrieves the ban and unban history of any user within the experience's universe. This method returns a BanHistoryPages instance that inherits from Pages.
This function call will only succeed on production game servers and not on client devices or in Studio.
This API uses the User Restrictions Open Cloud API. You will be able to utilize these APIs to manage your bans in third party applications.
Parameters
Returns
See BanHistoryPages for return reference.
GetCharacterAppearanceInfoAsync
This function returns information about a player's avatar (ignoring gear) on the Roblox website in the form of a dictionary. It is not to be confused with GetCharacterAppearanceAsync, which actually loads the assets described by this method. You can use InsertService:LoadAsset() to load the assets that are used in the player's avatar. The structure of the returned dictionary is as follows:
Name | Type | Description |
---|---|---|
assets | table (see below) | Describes the equipped assets (hats, body parts, etc) |
bodyColors | table (see below) | Describes the BrickColor values for each limb |
bodyColor3s | table (see below) | Describes the Color3 instance for each limb which may not match perfectly with bodyColors |
defaultPantsApplied | bool | Describes whether default pants are applied |
defaultShirtApplied | bool | Describes whether default shirt is applied |
emotes | table (see below) | Describes the equipped emote animations |
playerAvatarType | string | Either "R15" or "R6" |
scales | table (see below) | Describes various body scaling factors |
Assets Sub-Table
The assets table is an array of tables containing the following keys that describe the assets currently equipped by the player:
Name | Type | Description |
---|---|---|
id | number | The asset ID of the equipped asset |
assetType | table | A table with name and id fields, each describing the kind of asset equipped ("Hat", "Face", etc.) |
name | string | The name of the equipped asset |
Scales Sub-Table
The scales table has the following keys, each a number corresponding to one Humanoid scaling property: bodyType, head, height, proportion, depth, width.
Body Colors Sub-Table
The bodyColors table has the following keys, each a number corresponding to a BrickColor ID number which can be used with BrickColor.new(id): leftArmColorId, torsoColorId, rightArmColorId, headColorId, leftLegColorId, rightLegColorId.
Parameters
The *userId of the specified player.
Returns
A dictionary containing information about the character appearance of a given user.
Code Samples
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
The GetFriends Players function returns a FriendPages object which contains information for all of the given user's friends. The items within the FriendPages object are tables with the following fields:
Name | Type | Description |
---|---|---|
Id | int64 | The friend's UserId |
Username | string | The friend's username |
DisplayName | string | The display name of the friend. |
See the code samples for an easy way to iterate over all a player's friends.
Parameters
The user ID of the player being specified.
Returns
Code Samples
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
Returns the HumanoidDescription for a specified outfitId, which will be set with the parts/colors/Animations etc of the outfit. An outfit can be one created by a user, or it can be the outfit for a bundle created by Roblox.
Parameters
The id of the outfit for which the HumanoidDescription is sought.
Returns
HumanoidDescription initialized with the specification for the passed in outfitId.
Code Samples
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
Returns a HumanoidDescription which specifies everything equipped for the avatar of the user specified by the passed in userId. Also includes scales and body colors.
Parameters
The userId for a Roblox user. (The UserId is the number in the profile of the user e.g www.roblox.com/users/1/profile).
Returns
HumanoidDescription initialized with the passed in user's avatar specification.
Code Samples
game.Players:CreateHumanoidModelFromDescription(game.Players:GetHumanoidDescriptionFromUserId(1), Enum.HumanoidRigType.R15).Parent = game.Workspace
GetNameFromUserIdAsync
The GetNameFromUserIdAsync Players function will send a query to the Roblox website asking what the username is of the account with the given UserId.
This method errors if no account exists with the given UserId. If you aren't certain such an account exists, it's recommended to wrap calls to this function with pcall. In addition, you can manually cache results to make future calls with the same UserId fast. See the code samples to learn more.
Parameters
The Player.UserId of the player being specified.
Returns
The name of a user with the specified Player.UserId.
Code Samples
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"
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
This function will send a query to the Roblox website asking what the Player.UserId is of the account with the given Player name.
This method errors if no account exists with the given username. If you aren't certain such an account exists, it's recommended to wrap calls to this function with pcall. In addition, you can manually cache results to quickly make future calls with the same username. See the code samples to learn more.
Parameters
The username of the player being specified.
Returns
The Player.UserId of a user whose name is specified.
Code Samples
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"
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
This function returns the content URL of an image of a player's avatar given their UserId, the desired image size as a Enum.ThumbnailSize enum, and the desired type as a Enum.ThumbnailType enum. It also returns a boolean describing if the image is ready to use.
Most often, this method is used with ImageLabel.Image or Decal.Texture to display user avatar pictures in an experience.
Parameters
The Player.UserId of the player being specified.
A Enum.ThumbnailType describing the type of thumbnail.
A Enum.ThumbnailSize specifying the size of the thumbnail.
Returns
A tuple containing the content URL of a user thumbnail based on the specified parameters, and a bool describing if the image is ready to be used or not.
Code Samples
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
Unbans players banned from Players:BanAsync() or the User Restrictions Open Cloud API.
Like Players:BanAsync(), this method takes in a config dictionary that will let you bulk unban users. This configures the users that are unbanned and the scope from which they are unbanned from.
Unbans will only take effect on bans with the same ApplyToUniverse scope. For example, an unban with ApplyToUniverse set to true will not invalidate a previous ban with ApplyToUniverse set to false. In other words, a universe level unban will not invalidate a place level ban. The opposite also holds true.
This method invokes a HTTP call to backend services, which are throttled and may fail. If you are calling this API with multiple UserIds, this method will attempt to make this HTTP call for each UserId. It will then aggregate any error messages and join them as a comma separated list. For example, if this method is invoked for five UserIds: {1, 2, 3, 4, 5} and requests for users 2 and 4 fail then the following error message appears: HTTP failure for UserId 2: Timedout, HTTP 504 (Service unavailable) failure for UserId 4: Service exception. The message will always include failure for UserId {} if it is an HTTP error. It is undefined behavior if you pass in both valid and invalid UserIds, i.e. a UserId that is not a positive number, as some network requests may succeed before all input is validated.
Because of the risks associated with banning users, this method may only be called on the backend game server. Client side calls will result in an error. You may test this API in Studio, Team Create, and Team Test, but the bans will not apply to production. This function call will only attempt ban requests on production game servers and not in Studio testing. However, all input validation steps will still work in Studio.
This API uses the User Restrictions Open Cloud API. You will be able to utilize these APIs to manage your bans in third party applications.
Parameters
Name | Type | Description |
---|---|---|
UserIds | array | UserIDs to be force allowed into the experience(s). Max size is 50. |
ApplyToUniverse | boolean | Propagates the unban to all places within this universe. |
Returns
Code Samples
local Players = game:GetService("Players")
if shouldBeUnbanned(player: 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
Events
PlayerAdded
The PlayerAdded event fires when a player enters the game. This is used to fire an event when a player joins a game, such as loading the player's saved GlobalDataStore data.
This can be used alongside the Players.PlayerRemoving event, which fires when a player is about to leave the game. For instance, if you would like print a message every time a new player joins or leaves the game:
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)
If you want to track when a player's character is added or removed from the game, such as when a player respawns or dies, you can use the Player.CharacterAdded and Player.CharacterRemoving functions.
Note that this event does not work as expected in Play mode because the player is created before scripts run that connect to PlayerAdded. To handle this case, as well as cases in which the script is added into the game after a player enters, create an onPlayerAdded() function that you can call to handle a player's entrance.
Parameters
An instance of the player that joined the game.
Code Samples
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print("A player has entered: " .. player.Name)
end
Players.PlayerAdded:Connect(onPlayerAdded)
PlayerMembershipChanged
This event fires when the game server recognizes that a player's membership has changed. Note, however, that the server will only attempt to check and update the membership after the Premium modal has been closed. Thus, to account for cases where the user purchases Premium outside of the game while playing, you must still prompt them to purchase Premium; this will then show a message telling them they're already upgraded and, once they close the modal, the game server will update their membership and trigger this event.
To learn more about and incorporating Premium into your experience and monetizing with the engagement-based payouts system, see Engagement-Based Payouts.
See also:
- MarketplaceService:PromptPremiumPurchase(), used to prompt a user to purchase Premium
- MarketplaceService.PromptPremiumPurchaseFinished, fires when the Premium purchase UI closes
Parameters
Code Samples
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
The PlayerRemoving event fires right before a Player leaves the game. This event fires before ChildRemoved does on Players, and behaves somewhat similarly to Instance.DescendantRemoving. Since it fires before the actual removal of a Player, this event is useful for storing player data using a GlobalDataStore.
This can be used alongside the Player.PlayerAdded event, which fires when a player joins the game. For instance, to print a message every time a new player joins or leaves the game:
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)
If you want to track when a player's character is added or removed from the game, such as when a player respawns or dies, you can use the Player.CharacterAdded and Player.CharacterRemoving functions.
Parameters
An instance of the player that is leaving the game.
Code Samples
local Players = game:GetService("Players")
local function onPlayerRemoving(player)
print("A player has left: " .. player.Name)
end
Players.PlayerRemoving:Connect(onPlayerRemoving)
UserSubscriptionStatusChanged
This event fires when the game server recognizes that the user's status for a certain subscription has changed. Note that the server only attempts to check and update the status after the Subscription Purchase modal has been closed. To account for cases in which the user purchases the subscription outside of the game while playing, you must still prompt them to purchase the subscription; the prompt shows a message telling the user they're already subscribed, and after they close the modal, the game server updates their subscription status and triggers this event.
Note that only server scripts receive this event.
Parameters
User whose subscription status has changed.
The ID of the subscription with a status change.