Players

Show Deprecated
Not Creatable
Service

The Players game service contains only Player objects for presently connected clients to a Roblox game server. It also contains information about a place's configuration (such as bubble chat or classic chat). It can fetch information about players not connected to the server, such as character appearances, friends and avatar thumbnail.

Code Samples

Give Sparkles to Everyone

1local Players = game:GetService("Players")
2
3local function onCharacterAdded(character)
4 -- Give them sparkles on their head if they don't have them yet
5 if not character:FindFirstChild("Sparkles") then
6 local sparkles = Instance.new("Sparkles")
7 sparkles.Parent = character:WaitForChild("Head")
8 end
9end
10
11local function onPlayerAdded(player)
12 -- Check if they already spawned in
13 if player.Character then
14 onCharacterAdded(player.Character)
15 end
16 -- Listen for the player (re)spawning
17 player.CharacterAdded:Connect(onCharacterAdded)
18end
19
20Players.PlayerAdded:Connect(onPlayerAdded)

Summary

Properties

Indicates whether or not bubble chat is enabled. It is set with the Players:SetChatStyle() method.

READ ONLY
NOT REPLICATED

Indicates whether Characters will respawn automatically.

NOT REPLICATED

Indicates whether or not classic chat is enabled; set by the Players:SetChatStyle() method.

READ ONLY
NOT REPLICATED

The Player that the LocalScript is running for.

READ ONLY
NOT REPLICATED

The maximum amount of players that can be in this server.

READ ONLY
NOT REPLICATED

The preferred amount of players for this server.

READ ONLY
NOT REPLICATED

Controls the amount of time taken for a players character to respawn.

Events

FriendRequestEvent(player: Player, player: Player, friendRequestEvent: FriendRequestEvent): RBXScriptSignal  



Fires when a player enters the game.

PlayerChatted(chatType: PlayerChatType, player: Player, message: string, targetPlayer: Player): RBXScriptSignal  

Fired when a player chats.


Fired when a player is connecting to the game.


Fired when a player is disconnecting from the game.


Fires when the game server recognizes that a player's membership has changed.


Fired when a player rejoins a game session after having disconnected prior.


Fires when a player is about to leave the game.

Methods

Chat(message: string): nil  

Makes the local player chat the given message.


Manually trigger creating Player.LocalPlayer.


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.

ReportAbuse(player: Player, reason: string, optionalMessage: string): nil  

Attempts to report the given player for the given reason.

ReportAbuseV3(player: Player, jsonTags: string): nil  



Sets whether BubbleChat and ClassicChat are being used, and tells TeamChat and Chat what to do.

SetLocalPlayerInfo(userId: number, userName: string, displayName: string, membershipType: MembershipType, isUnder13: boolean): nil  


TeamChat(message: string): nil  

Makes the LocalPlayer chat the given message, which will only be viewable by users on the same team.

WhisperChat(message: string, player: Instance): nil  

Delivers the given message to a recipient without anyone else seeing.

CreateHumanoidModelFromDescription(description: HumanoidDescription, rigType: HumanoidRigType, assetTypeVerification: AssetTypeVerification): Model  YIELDS

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.


Returns information about the character appearance of a given user.

GetFriendsAsync(userId: number): FriendPages  YIELDS

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.

GetUserIdFromNameAsync(userName: string): number  YIELDS

Sends a query to the Roblox website for the userId of an account with a given username.

GetUserThumbnailAsync(userId: number, thumbnailType: ThumbnailType, thumbnailSize: ThumbnailSize): Tuple  YIELDS

Returns the content URL of a player thumbnail given the size and type (avatar, bust, headshot), and a bool describing if the image is ready to be used.

Properties

BubbleChat

Read Only
Not Replicated

The BubbleChat Players property indicates whether or not bubble chat is enabled. It is set with the Players:SetChatStyle() method using the 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

Not Replicated

The CharacterAutoLoads Players property indicates whether Characters will respawn automatically. The default value is true.

If this property is disabled (false), players Characters will not spawn until the Player:LoadCharacter() function is called for each Player - including when players join the game.

This can be useful in games where players have finite lives, such as competitive games in which players do not respawn until a game round ends.

ClassicChat

Read Only
Not Replicated

Indicates whether or not classic chat is enabled. This property is set by the Players:SetChatStyle() method using the 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

Read Only
Not Replicated

LocalPlayer is a read-only property which refers to the Player whose client is running the game.

This property is only defined for LocalScripts (and ModuleScripts required by them), as they run on the client. For the server (on which Script objects run their code), this property is nil.

This property is useful in LocalScripts which display information about the player viewing a GUI. Using For example, if there were IntValue parented to a Player named "Coins" which represented how much money that player has, you could use the following to display this value for them:


1-- This code is appropriate for a LocalScript in StarterGui,
2-- for example: game.StarterGui.ScreenGui.TextLabel.LocalScript
3
4local player = game:GetService("Players").LocalPlayer
5-- Wait for a value we're expecting for the server to have created
6local vCoins = player:WaitForChild("Coins")
7
8local textLabel = script.Parent
9local function update()
10 textLabel.Text = "Coins: " .. vCoins.Value
11end
12
13-- Update once, then every time the value changes
14update()
15vCoins.Changed:Connect(update)
16

Loading GUIs

When creating loading GUIs using ReplicatedFirst, sometimes a LocalScript can run before the LocalPlayer is available. In this case, you should yield until it becomes available by using Instance:GetPropertyChangedSignal()


1local Players = game:GetService("Players")
2-- Below: access Players.LocalPlayer; if it is nil, we'll wait for it using GetPropertyChangedSignal.
3local player = Players.LocalPlayer or Players:GetPropertyChangedSignal("LocalPlayer"):wait()
4

Doing this isn't for a LocalScript within StarterGui, StarterPlayerScripts or StarterCharacterScripts: these scripts can only run after a Player object is already available, and LocalPlayer will have been set by then.

MaxPlayers

Read Only
Not Replicated

The MaxPlayers Players property determines the maximum amount of players that can be in this server.

While this property cannot be set through Scripts or LocalScripts in-game, it can be set from the place settings' Access tab on the site.

You can change this value depending on the number of player's you would like to limit in a single server. The number of players in a server affects the feel of your game and it's performance.

PreferredPlayers

Read Only
Not Replicated

The PreferredPlayers property determines the number of players to which Roblox's matchmaker will fill servers. This number should be less than the maximum number of players supported by the game in order to leave some spaces for additional players (such as friends or those following another player) to join.

This property can be set from the place settings' Access tab on the site. It cannot be set through Scripts or LocalScripts in-game.

When a player press the Play button to join a game server, Roblox attempts to match that player to a server such that the player count will try not to exceed PreferredPlayers. If a friend (or friends) of the player are in a server that is not full, Roblox prioritizes that server instead.

Example

There are 8 players in a server where the Player.MaximumPlayers is 10 and the PreferredPlayers is 8. A player presses the play button:

  • If the player has at least one friend in the server, Roblox selects the already-existing server so the player can play with their friend.
  • If the player has no friends in the server, a new server is started since the existing server has met the number of PreferredPlayers (the player could still join the server by manually selecting it or following another user).

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.

RespawnTime property in Studio Explorer Window

This is useful when you want to change how long it takes to respawn based on the type of your game but don't want to handle spawning players individually. Social games may want to decrease the respawn time whereas action games may want to increase it.

Although this can be set from within a Script, you will likely set the property from within Studio via the Players service property window.


1local Players = game:GetService(“Players”)
2Players.RespawnTime = 10.0
3

See also:

Events

FriendRequestEvent

Roblox Script Security

Parameters

player: Player
player: Player
friendRequestEvent: FriendRequestEvent

GameAnnounce

Roblox Script Security

Parameters

message: string

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:


1local Players = game:GetService("Players")
2
3Players.PlayerAdded:Connect(function(player)
4 print(player.Name .. " joined the game!")
5end)
6
7Players.PlayerRemoving:Connect(function(player)
8 print(player.Name .. " left the game!")
9end)
10

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.

  • Up until recently, this event didn't work on the client (in Localscripts), but this has been changed

  • This event does not work as expected in solo mode, because the player is created before scripts that connect to PlayerAdded run. 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

player: Player

An instance of the player that joined the game.


Code Samples

Players.PlayerAdded

1local Players = game:GetService("Players")
2
3local function onPlayerAdded(player)
4 print("A player has entered: " .. player.Name)
5end
6
7Players.PlayerAdded:Connect(onPlayerAdded)

PlayerChatted

Local User Security

The PlayerChatted Players event fires when a player chats.

The value of the PlayerChatType determines the type of chat sent. There are three types of chat: | Type | Description | |---------|-----------------------------------------------------------------------------------------------------------------------------------------------------------| | All | A global message that everyone can receive. | | Team | A team message only players in the same team can receive. | | Whisper | A whispered message only the person it's whispered to can receive. If the chat type is a Whisper Chat, the targetPlayer is the player being whispered to. |

Note that this event is not intended for wide use and will not work in Scripts or LocalScripts.

Parameters

chatType: PlayerChatType

The type of chat. Either all, team, or whisper.

player: Player

The player chatting (sending the message).

message: string

The message being chatted.

targetPlayer: Player

The player receiving the message if the chat is a whisper.


Code Samples

Checking Player Chatted in Command Bar

1local Players = game:GetService("Players")
2
3local function onPlayerChatted(playerChatType, sender, message, recipient)
4 print(sender.Name, "-", message, "-", playerChatType, "-", (recipient or "All"))
5end
6
7Players.PlayerChatted:Connect(onPlayerChatted)

PlayerConnecting

Local User Security

The PlayerConnecting Players event fires when a player is connecting to the game. It indicates the Player instance connecting.

This event is not intended for wide use and will not work in Scripts or LocalScripts. Instead, you can use the Player.PlayersAdded and Players.PlayerRemoving events.

Similarly, 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

player: Player

The Player connecting.


Code Samples

Player Connecting Disconnecting and Rejoining

1local Players = game:GetService("Players")
2
3Players.PlayerConnecting:Connect(function(player)
4 print(player.Name .. " connecting!")
5end)
6
7Players.PlayerDisconnecting:Connect(function(player)
8 print(player.Name .. " disconnecting!")
9end)
10
11Players.PlayerRejoining:Connect(function(player)
12 print(player.Name .. " rejoining!")
13end)

PlayerDisconnecting

Local User Security

The PlayerDisconnecting Players event fires when a player is disconnecting from the game. It indicates the Player instance disconnecting.

This event is not intended for wide use and will not work in Scripts or LocalScripts. Instead, you can use the Player.PlayersAdded and Players.PlayerRemoving events.

Similarly, 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

player: Player

The Player disconnecting.


Code Samples

Player Connecting Disconnecting and Rejoining

1local Players = game:GetService("Players")
2
3Players.PlayerConnecting:Connect(function(player)
4 print(player.Name .. " connecting!")
5end)
6
7Players.PlayerDisconnecting:Connect(function(player)
8 print(player.Name .. " disconnecting!")
9end)
10
11Players.PlayerRejoining:Connect(function(player)
12 print(player.Name .. " rejoining!")
13end)

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 game, and monetizing your game with the Premium Payouts system, take a look at this article.

See also:

Parameters

player: Player

Code Samples

Handling Premium Membership Changes

1local Players = game:GetService("Players")
2
3local function grantPremiumBenefits(player)
4 -- Grant the player access to Premium-only areas, items, or anything you can imagine!
5 print("Giving", player, "premium benefits!")
6end
7
8local function playerAdded(player)
9 if player.MembershipType == Enum.MembershipType.Premium then
10 grantPremiumBenefits(player)
11 end
12end
13
14local function playerMembershipChanged(player)
15 print("Received event PlayerMembershipChanged. New membership = " .. tostring(player.MembershipType))
16 if player.MembershipType == Enum.MembershipType.Premium then
17 grantPremiumBenefits(player)
18 end
19end
20
21Players.PlayerAdded:Connect(playerAdded)
22Players.PlayerMembershipChanged:Connect(playerMembershipChanged)

PlayerRejoining

Local User Security

The PlayerRejoining Players event fires when a player rejoins a game session after having disconnected prior. It indicates the Player instance rejoining.

This event is not intended for wide use and will not work in Scripts or LocalScripts. Instead, you can use the Player.PlayersAdded and Players.PlayerRemoving events.

Similarly, 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

player: Player

The Player rejoining the game.


Code Samples

Player Connecting Disconnecting and Rejoining

1local Players = game:GetService("Players")
2
3Players.PlayerConnecting:Connect(function(player)
4 print(player.Name .. " connecting!")
5end)
6
7Players.PlayerDisconnecting:Connect(function(player)
8 print(player.Name .. " disconnecting!")
9end)
10
11Players.PlayerRejoining:Connect(function(player)
12 print(player.Name .. " rejoining!")
13end)

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:


1local Players = game:GetService("Players")
2
3Players.PlayerAdded:Connect(function(player)
4 print(player.Name .. " joined the game!")
5end)
6
7Players.PlayerRemoving:Connect(function(player)
8 print(player.Name .. " left the game!")
9end)
10

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

player: Player

An instance of the player that is leaving the game.


Code Samples

Players.PlayerRemoving

1local Players = game:GetService("Players")
2
3local function onPlayerRemoving(player)
4 print("A player has left: " .. player.Name)
5end
6
7Players.PlayerRemoving:Connect(onPlayerRemoving)

Methods

Chat

Plugin Security

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

message: string

The message chatted.


Returns

No return.

Code Samples

Players:Chat

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

CreateLocalPlayer

Local User Security

The LocalPlayer will be set automatically when a client connects to the game, so uses for this method are extremely limited. This function is protected, attempting to use it in a Script or LocalScript will cause an error.

Although you cannot create the LocalPlayer, you can reference the LocalPlayer created by a game using the following code in a LocalScript:


1 local player = game.Players.LocalPlayer
2

Returns

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:


1local Players = game:GetService("Players")
2local function getPlayerByUserId(userId)
3 for _, player in pairs(Players:GetPlayers()) do
4 if player.UserId == userId then
5 return player
6 end
7 end
8end
9

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

userId: number

The Player.UserId of the player being specified.


Returns

Code Samples

ProcessReceipt Callback

1local MarketplaceService = game:GetService("MarketplaceService")
2local DataStoreService = game:GetService("DataStoreService")
3local Players = game:GetService("Players")
4
5-- Data store for tracking purchases that were successfully processed
6local purchaseHistoryStore = DataStoreService:GetDataStore("PurchaseHistory")
7
8-- Table setup containing product IDs and functions for handling purchases
9local productFunctions = {}
10-- ProductId 123123 for a full heal
11productFunctions[123123] = function(_receipt, player)
12 -- Logic/code for player buying a full heal (may vary)
13 if player.Character and player.Character:FindFirstChild("Humanoid") then
14 -- Heal the player to full health
15 player.Character.Humanoid.Health = player.Character.Humanoid.MaxHealth
16 -- Indicate a successful purchase
17 return true
18 end
19end
20-- ProductId 456456 for 100 gold
21productFunctions[456456] = function(_receipt, player)
22 -- Logic/code for player buying 100 gold (may vary)
23 local stats = player:FindFirstChild("leaderstats")
24 local gold = stats and stats:FindFirstChild("Gold")
25 if gold then
26 gold.Value = gold.Value + 100
27 -- Indicate a successful purchase
28 return true
29 end
30end
31
32-- The core 'ProcessReceipt' callback function
33local function processReceipt(receiptInfo)
34 -- Determine if the product was already granted by checking the data store
35 local playerProductKey = receiptInfo.PlayerId .. "_" .. receiptInfo.PurchaseId
36 local purchased = false
37 local success, result, errorMessage
38
39 success, errorMessage = pcall(function()
40 purchased = purchaseHistoryStore:GetAsync(playerProductKey)
41 end)
42 -- If purchase was recorded, the product was already granted
43 if success and purchased then
44 return Enum.ProductPurchaseDecision.PurchaseGranted
45 elseif not success then
46 error("Data store error:" .. errorMessage)
47 end
48
49 -- Determine if the product was already granted by checking the data store
50 local playerProductKey = receiptInfo.PlayerId .. "_" .. receiptInfo.PurchaseId
51
52 local success, isPurchaseRecorded = pcall(function()
53 return purchaseHistoryStore:UpdateAsync(playerProductKey, function(alreadyPurchased)
54 if alreadyPurchased then
55 return true
56 end
57
58 -- Find the player who made the purchase in the server
59 local player = Players:GetPlayerByUserId(receiptInfo.PlayerId)
60 if not player then
61 -- The player probably left the game
62 -- If they come back, the callback will be called again
63 return nil
64 end
65
66 local handler = productFunctions[receiptInfo.ProductId]
67
68 local success, result = pcall(handler, receiptInfo, player)
69 -- If granting the product failed, do NOT record the purchase in datastores.
70 if not success or not result then
71 error("Failed to process a product purchase for ProductId:", receiptInfo.ProductId, " Player:", player)
72 return nil
73 end
74
75 -- Record the transcation in purchaseHistoryStore.
76 return true
77 end)
78 end)
79
80 if not success then
81 error("Failed to process receipt due to data store error.")
82 return Enum.ProductPurchaseDecision.NotProcessedYet
83 elseif isPurchaseRecorded == nil then
84 -- Didn't update the value in data store.
85 return Enum.ProductPurchaseDecision.NotProcessedYet
86 else
87 -- IMPORTANT: Tell Roblox that the game successfully handled the purchase
88 return Enum.ProductPurchaseDecision.PurchaseGranted
89 end
90end
91
92-- Set the callback; this can only be done once by one script on the server!
93MarketplaceService.ProcessReceipt = processReceipt
94
Players:GetPlayerByUserId

1local Players = game:GetService("Players")
2
3local player = Players:GetPlayerByUserId(1)
4
5if player then
6 print("Player with userId 1 is in this server! Their name is: " .. player.Name)
7else
8 print("Player with userId 1 is not in this server!")
9end

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:


1local function getPlayerFromCharacter(character)
2 for _, player in pairs(game:GetService("Players"):GetPlayers()) do
3 if player.Character == character then
4 return player
5 end
6 end
7end
8

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

character: Model

A character instance that you want to get the player from.


Returns

Code Samples

Players:GetPlayerFromCharacter

1local Players = game:GetService("Players")
2
3local character = workspace.Player
4local player = Players:GetPlayerFromCharacter(character)
5
6if player then
7 print("Player is " .. player.Name)
8else
9 print("Player doesn't exist!")
10end

GetPlayers

This method returns a table of all presently connected Player. It functions the same way Instance:GetChildren() would except that it only returns Player objects. It functions similarly to Instance:GetChildren() when called on Players. 0 When used in conjunction with a for-loop, it is useful for iterating over all players in a game.


1Players = game:GetService("Players")
2for i, player in pairs(Players:GetPlayers()) do
3 print(player.Name)
4end
5

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!


1local Players = game:GetService("Players")
2
3local function onPlayerAdded(player)
4 print("Player: " .. player.Name)
5end
6
7for _, player in pairs(Players:GetPlayers()) do
8 onPlayerAdded(player)
9end
10Players.PlayerAdded:Connect(onPlayerAdded)
11

Returns

A table containing all the players in the server.

Code Samples

Give Sparkles to Everyone

1local Players = game:GetService("Players")
2
3local function onCharacterAdded(character)
4 -- Give them sparkles on their head if they don't have them yet
5 if not character:FindFirstChild("Sparkles") then
6 local sparkles = Instance.new("Sparkles")
7 sparkles.Parent = character:WaitForChild("Head")
8 end
9end
10
11local function onPlayerAdded(player)
12 -- Check if they already spawned in
13 if player.Character then
14 onCharacterAdded(player.Character)
15 end
16 -- Listen for the player (re)spawning
17 player.CharacterAdded:Connect(onCharacterAdded)
18end
19
20Players.PlayerAdded:Connect(onPlayerAdded)

ReportAbuse

Local User Security

This function attempts to report the given player for the given reason. Since this item is protected, attempting to use it in a Script or LocalScript will cause an error.

The game uses this function internally when a player interact's with the game's default report system. Players should use this system to report players for offensive or inappropriate behavior.

Parameters

player: Player

The player being reported.

reason: string

The reason for reporting the player.

optionalMessage: string

An optional message providing more details about the reported abuse.


Returns

No return.

ReportAbuseV3

Roblox Script Security

Parameters

player: Player
jsonTags: string

Returns

SetChatStyle

Plugin Security

This function sets whether BubbleChat and ClassicChat are being used, and tells TeamChat and Chat what to do using the 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

style: ChatStyle

The specified chat style being set.

Default Value: "Classic"

Returns

No return.

Code Samples

Setting a Player's Chat Style

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

SetLocalPlayerInfo

Roblox Script Security

Parameters

userId: number
userName: string
displayName: string
membershipType: MembershipType
isUnder13: boolean

Returns

TeamChat

Plugin Security

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

message: string

The message being chatted.


Returns

No return.

Code Samples

Sending Team Chat

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

WhisperChat

Local User Security

Thisfunction delivers the given message to a recipient without anyone else seeing. Since this item is protected, attempting to use it in aClass.ScriptorClass.LocalScript` will cause an error.

This function is used internally when the Players.LocalPlayer sends whispers another player.

Parameters

message: string

The message being chatted.

player: Instance

The recipient Player.


Returns

No return.

CreateHumanoidModelFromDescription

Yields

Returns a character Model equipped with everything specified in the passed in HumanoidDescription, and is R6 or R15 as specified by the rigType.

Parameters

description: HumanoidDescription

Specifies the appearance of the returned character.

Specifies whether the returned character will be R6 or R15.

assetTypeVerification: AssetTypeVerification

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).

Default Value: "Default"

Returns

A Humanoid character Model.

Code Samples

Create Humanoid Model From A User ID

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

CreateHumanoidModelFromUserId

Yields

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

userId: number

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

Create Humanoid Model From Description

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

GetCharacterAppearanceInfoAsync

Yields

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:

NameTypeDescription
bodyColorstable (see below)Describes the BrickColor values for each limb
assetstable (see below)Describes the equipped assets (hats, body parts, etc)
defaultPantsAppliedboolDescribes whether default pants are applied
defaultShirtAppliedboolDescribes whether default shirt is applied
playerAvatarTypestringEither "R15" or "R6"
scalestable (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:

NameTypeDescription
idnumberThe asset ID of the equipped asset
assetTypetableA table with name and id fields, each describing the kind of asset equipped ("Hat", "Face", etc.)
namestringThe 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 body colors table has the following keys, each a number corresponding to a BrickColor ID number which can be used with BrickColor.new(): leftArmColorId, torsoColorId, rightArmColorId, headColorId, leftLegColorId, rightLegColorId.

Parameters

userId: number

The *userId of the specified player.


Returns

A dictionary containing information about the character appearance of a given user.

Code Samples

Example Return Character Appearance Dictionary

1local result = {
2 playerAvatarType = "R15",
3 defaultPantsApplied = false,
4 defaultShirtApplied = false,
5 scales = {
6 bodyType = 0,
7 head = 1,
8 height = 1.05,
9 proportion = 0,
10 depth = 0.92,
11 width = 0.85,
12 },
13 bodyColors = {
14 leftArmColorId = 1030,
15 torsoColorId = 1001,
16 rightArmColorId = 1030,
17 headColorId = 1030,
18 leftLegColorId = 1001,
19 rightLegColorId = 1001,
20 },
21 assets = {
22 {
23 id = 1031492,
24 assetType = {
25 name = "Hat",
26 id = 8,
27 },
28 name = "Striped Hat",
29 },
30 {
31 id = 13062491,
32 assetType = {
33 name = "Face Accessory",
34 id = 42,
35 },
36 name = "Vision Française ",
37 },
38 {
39 id = 16598440,
40 assetType = {
41 name = "Neck Accessory",
42 id = 43,
43 },
44 name = "Red Bow Tie",
45 },
46 {
47 id = 28999228,
48 assetType = {
49 name = "Face",
50 id = 18,
51 },
52 name = "Joyous Surprise",
53 },
54 {
55 id = 86896488,
56 assetType = {
57 name = "Shirt",
58 id = 11,
59 },
60 name = "Expensive Red Tuxedo Jacket",
61 },
62 {
63 id = 86896502,
64 assetType = {
65 name = "Pants",
66 id = 12,
67 },
68 name = "Expensive Red Tuxedo Pants",
69 },
70 {
71 id = 376530220,
72 assetType = {
73 name = "Left Arm",
74 id = 29,
75 },
76 name = "ROBLOX Boy Left Arm",
77 },
78 {
79 id = 376531012,
80 assetType = {
81 name = "Right Arm",
82 id = 28,
83 },
84 name = "ROBLOX Boy Right Arm",
85 },
86 {
87 id = 376531300,
88 assetType = {
89 name = "Left Leg",
90 id = 30,
91 },
92 name = "ROBLOX Boy Left Leg",
93 },
94 {
95 id = 376531703,
96 assetType = {
97 name = "Right Leg",
98 id = 31,
99 },
100 name = "ROBLOX Boy Right Leg",
101 },
102 {
103 id = 376532000,
104 assetType = {
105 name = "Torso",
106 id = 27,
107 },
108 name = "ROBLOX Boy Torso",
109 },
110 },
111}
112
113print(result)

GetFriendsAsync

Yields

The GetFriends Players function returns a FriendPages object which contains information for all of the given Player's friends. The items within the FriendPages object are tables with the following fields:

NameTypeDescription
Idint64The friend's UserId
UsernamestringThe friend's username
DisplayNamestringThe `Class.Player.DisplayName|display name` of the friend.
IsOnlineboolIf the friend is currently online

See the code samples for an easy way to iterate over all a player's friends.

Parameters

userId: number

The userId of the player being specified.


Code Samples

Print Roblox Friends

1local Players = game:GetService("Players")
2
3local USERNAME = "Cozecant"
4
5local function iterPageItems(pages)
6 return coroutine.wrap(function()
7 local pagenum = 1
8 while true do
9 for _, item in ipairs(pages:GetCurrentPage()) do
10 coroutine.yield(item, pagenum)
11 end
12 if pages.IsFinished then
13 break
14 end
15 pages:AdvanceToNextPageAsync()
16 pagenum = pagenum + 1
17 end
18 end)
19end
20
21-- First, get the user ID of the player
22local userId = Players:GetUserIdFromNameAsync(USERNAME)
23-- Then, get a FriendPages object for their friends
24local friendPages = Players:GetFriendsAsync(userId)
25-- Iterate over the items in the pages. For FriendPages, these
26-- are tables of information about the friend, including Username.
27-- Collect each username in a table
28local usernames = {}
29for item, _pageNo in iterPageItems(friendPages) do
30 table.insert(usernames, item.Username)
31end
32
33print("Friends of " .. USERNAME .. ": " .. table.concat(usernames, ", "))

GetHumanoidDescriptionFromOutfitId

Yields

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

outfitId: number

The id of the outfit for which the HumanoidDescription is sought.


Returns

HumanoidDescription initialized with the specification for the passed in outfitId.

Code Samples

Get HumanoidDescription From Outfit ID

1local function getHumanoidDescriptionBundle(bundleId)
2 local function getOutfitId()
3 if bundleId <= 0 then
4 return
5 end
6 local info = game.AssetService:GetBundleDetailsAsync(bundleId)
7 if not info then
8 return
9 end
10 for _,item in pairs(info.Items) do
11 if item.Type == "UserOutfit" then
12 return item.Id
13 end
14 end
15 end
16 local itemId = getOutfitId(bundleId)
17 return (itemId and itemId > 0) and game.Players:GetHumanoidDescriptionFromOutfitId(itemId) or nil
18end
19game.Players:CreateHumanoidModelFromDescription(getHumanoidDescriptionBundle(799), Enum.HumanoidRigType.R15).Parent = game.Workspace

GetHumanoidDescriptionFromUserId

Yields

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

userId: number

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

Get HumanoidDescription From User ID

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

GetNameFromUserIdAsync

Yields

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

userId: number

The Player.UserId of the player being specified.


Returns

The name of a user with the specified Player.UserId.

Code Samples

Get Name from UserId using a cache

1local Players = game:GetService("Players")
2
3-- Create a table called 'cache' to store each 'Name' as they are found.
4-- If we lookup a 'Name' using the same 'UserId', the 'Name' will come
5-- from cache (fast) instead of GetNameFromUserIdAsync() (yields).
6local cache = {}
7
8function getNameFromUserId(userId)
9 -- First, check if the cache contains 'userId'
10 local nameFromCache = cache[userId]
11 if nameFromCache then
12 -- if a value was stored in the cache at key 'userId', then this 'nameFromCache'
13 -- is the correct Name and we can return it.
14 return nameFromCache
15 end
16
17 -- If here, 'userId' was not previously looked up and does not exist in the
18 -- cache. Now we need to use GetNameFromUserIdAsync() to look up the name
19 local name
20 local success, _ = pcall(function()
21 name = Players:GetNameFromUserIdAsync(userId)
22 end)
23 if success then
24 -- if 'success' is true, GetNameFromUserIdAsync() successfully found the
25 -- name. Store this name in the cache using 'userId' as the key so we
26 -- never have to look this name up in the future. Then return name.
27 cache[userId] = name
28 return name
29 end
30 -- If here, 'success' was false, meaning GetNameFromUserIdAsync()
31 -- was unable to find the 'name' for the 'userId' provided. Warn the user
32 -- this happened and then return nothing, or nil.
33 warn("Unable to find Name for UserId:", userId)
34 return nil
35end
36
37-- Example Data:
38-- UserId: 118271 Name: "RobloxRulez"
39-- UserId: 131963979 Name: "docsRule"
40
41-- The first time a UserId is used, GetNameFromUserIdAsync() will be called
42local nameOne = getNameFromUserId(118271)
43local nameTwo = getNameFromUserId(131963979)
44-- Because 118271 was previously used, get its Name from the cache
45local nameOneQuick = getNameFromUserId(118271)
46
47print(nameOne, nameTwo, nameOneQuick)
48-- prints: "RobloxRulez docsRule RobloxRulez"
49
Get Name from UserId

1local Players = game:GetService("Players")
2
3-- Example Data:
4-- UserId: 118271 Name: "RobloxRulez"
5-- UserId: 131963979 Name: "docsRule"
6
7local nameOne = Players:GetNameFromUserIdAsync(118271)
8local nameTwo = Players:GetNameFromUserIdAsync(131963979)
9
10print(nameOne, nameTwo)
11-- prints: "RobloxRulez docsRule"
12

GetUserIdFromNameAsync

Yields

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

userName: string

The username of the player being specified.


Returns

The Player.UserId of a user whose name is specified.

Code Samples

Get UserId from Name using a cache

1local Players = game:GetService("Players")
2
3-- Create a table called 'cache' to store each 'UserId' as they are found.
4-- If we lookup a 'UserId' using the same 'Name', the 'UserId' will come
5-- from cache (fast) instead of GetUserIdFromNameAsync() (yields).
6local cache = {}
7
8function getUserIdFromName(name)
9 -- First, check if the cache contains 'name'
10 local userIdFromCache = cache[name]
11 if userIdFromCache then
12 -- if a value was stored in the cache at key 'name', then this 'userIdFromCache'
13 -- is the correct UserId and we can return it.
14 return userIdFromCache
15 end
16
17 -- If here, 'name' was not previously looked up and does not exist in the
18 -- cache. Now we need to use GetUserIdFromNameAsync() to look up the userId
19 local userId
20 local success, _ = pcall(function()
21 userId = Players:GetUserIdFromNameAsync(name)
22 end)
23 if success then
24 -- if 'success' is true, GetUserIdFromNameAsync() successfully found the
25 -- userId. Store this userId in the cache using 'name' as the key so we
26 -- never have to look this userId up in the future. Then return userId.
27 cache[name] = userId
28 return userId
29 end
30 -- If here, 'success' was false, meaning GetUserIdFromNameAsync()
31 -- was unable to find the 'userId' for the 'name' provided. We can warn the
32 -- user this happened and then return nothing, or nil.
33 warn("Unable to find UserId for Name:", name)
34 return nil
35end
36
37-- Example Data:
38-- UserId: 118271 Name: "RobloxRulez"
39-- UserId: 131963979 Name: "docsRule"
40
41-- The first time a Name is used, GetUserIdFromNameAsync() will be called
42local userIdOne = getUserIdFromName("RobloxRulez")
43local userIdTwo = getUserIdFromName("docsRule")
44-- Because "RobloxRulez" was previously used, get its UserId from the cache
45local userIdOneQuick = getUserIdFromName("RobloxRulez")
46
47print(userIdOne, userIdTwo, userIdOneQuick)
48-- prints: "118271 131963979 118271"
49
Get UserId from Name

1local Players = game:GetService("Players")
2
3-- Example Data:
4-- UserId: 118271 Name: "RobloxRulez"
5-- UserId: 131963979 Name: "docsRule"
6
7local userIdOne = Players:GetUserIdFromNameAsync("RobloxRulez")
8local userIdTwo = Players:GetUserIdFromNameAsync("docsRule")
9print(userIdOne, userIdTwo)
10-- prints: "118271 131963979"
11

GetUserThumbnailAsync

Yields

This function fetches a content URL of an image of a player's avatar given their UserId, the image size (as an enum) and type (also an enum: avatar, bust, headshot). It also returns a bool describing if the image is ready to be used.

Most often, this method is used with ImageLabel.Image to display player pictures next to their username in-game. It is also appropriate for Decal.Texture as well.

Available Sizes

ThumbnailSize: Size48x48, Size60x60, Size100x100, Size150x150, Size180x180, Size353x353, Size420x420.

Types of User Thumbnails

Enum.ThumbnailTypeDescriptionExample (60px)
AvatarBustUpper chest and head
AvatarThumbnailEntire avatar
HeadShotJust the head and face

Parameters

userId: number

The Player.UserId of the player being specified.

thumbnailType: ThumbnailType

A ThumbnailType describing the type of thumbnail.

thumbnailSize: ThumbnailSize

A 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

Display Player Thumbnail

1local Players = game:GetService("Players")
2
3local player = Players.LocalPlayer
4
5local PLACEHOLDER_IMAGE = "rbxassetid://0" -- replace with placeholder image
6
7-- fetch the thumbnail
8local userId = player.UserId
9local thumbType = Enum.ThumbnailType.HeadShot
10local thumbSize = Enum.ThumbnailSize.Size420x420
11local content, isReady = Players:GetUserThumbnailAsync(userId, thumbType, thumbSize)
12
13-- set the ImageLabel's content to the user thumbnail
14local imageLabel = script.Parent
15imageLabel.Image = (isReady and content) or PLACEHOLDER_IMAGE
16imageLabel.Size = UDim2.new(0, 420, 0, 420)