Service · inherits Instance
Players
A service that contains presently connected Player objects.
About Players
Properties 9
BanningEnabled
: booleanNotScriptableEnables or disables the threePlayersmethods (BanAsync(),UnbanAsync(), andGetBanHistoryAsync()) that constitute the ban API. This property cannot be set through developer-facing Luau and must be set in Studio through the Players properties window.BubbleChat
: booleanReadOnlyNotReplicatedIndicates whether or not bubble chat is enabled. It is set with thePlayers.SetChatStylemethod.This property indicates whether or not bubble chat is enabled. It is set with the
Players.SetChatStylemethod using theChatStyleenum.When this chat mode is enabled, the experience displays chats in the chat user interface at the top-left corner of the screen.
There are two other chat modes,
Players.ClassicChatand a chat mode where both classic and bubble chat are enabled.CharacterAutoLoads
: booleanNotReplicatedIndicates whethercharacterswill respawn automatically.This property indicates whether
characterswill respawn automatically. The default value is true.If this property is disabled (false), player
characterswill not spawn until thePlayer.LoadCharacterAsyncfunction is called for eachPlayer, including when players join the experience.This can be useful in experiences where players have finite lives, such as competitive experiences in which players do not respawn until a round ends.
ClassicChat
: booleanReadOnlyNotReplicatedIndicates whether or not classic chat is enabled; set by thePlayers.SetChatStylemethod.Indicates whether or not classic chat is enabled. This property is set by the
Players.SetChatStylemethod using theChatStyleenum.When this chat mode is enabled, the experience displays chats in a bubble above the sender's head.
There are two other chat modes,
Players.BubbleChatand a chat mode where both classic and bubble chat are enabled.LocalPlayer
: PlayerReadOnlyNotReplicatedThePlayerthat theLocalScriptis running for.This read-only property refers to the
Playerwhose client is running the experience.This property is only defined for
LocalScriptsandModuleScriptsrequired by them, since they run on the client. For the server, on whichScriptobjects run their code, this property isnil.MaxPlayers
: intReadOnlyNotReplicatedThe maximum number of players that can be in a server.This 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.
PreferredPlayers
: intReadOnlyNotReplicatedThe preferred number of players for a server.This 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
: floatControls the amount of time taken for a players character to respawn.This property controls the time, in seconds, it takes for a player to respawn when
Players.CharacterAutoLoadsis 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 thePlayersobject in Studio's Explorer window.UseStrafingAnimations
: booleanNotScriptableDetermines whether R15 character models play directional strafing and backpedaling animations instead of always turning to face their direction of movement.When enabled, R15 character
Humanoidsplay directional locomotion animations, strafing sideways and backpedaling while keeping their current facing direction instead of rotating to face whichever direction they move. When disabled, characters turn to face their direction of movement. Defaults tofalse.This property cannot be set through developer-facing Luau and must be set in Studio through the
Playersproperties window.
Methods 19
BanAsync
(config: Dictionary) → ()YieldsBans 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. This method is enabled and disabled by thePlayers.BanningEnabledproperty, which you can toggle in Studio.The
Players.BanAsyncmethod 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, enable the ban to temporarily block the banned user's device from rejoining the experience, 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. This method is enabled and disabled by thePlayers.BanningEnabledproperty, which you can toggle in Studio.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.DisplayReasoncan 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
ApplyToUniversetofalse. 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, 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 alternate accounts. You can turn off ban propagations to alternate accounts by configuring
ExcludeAltAccountstotrue.Device Blocks
To help address disruptive users who circumvent alternate account detection, set
ApplyDeviceBlocktotrue. This blocks the banned user's device from rejoining the experience for 24 hours after the ban is applied.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
Durationfield. 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 usingPlayers.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 underPrivateReasonwhich can be up to 1000 characters and are not text filtered.PrivateReasonnotes 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 withUserIds2 and 4 fail, the following error message appears:HTTP failure for UserId 2: Timedout, HTTP 504 (Service unavailable) failure for UserId 4: Service exceptionThe 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.
Chat
(message: string) → ()PluginMakes the local player chat the given message.This function makes the local player chat the given message. Since this item is protected, attempting to use it in a
ScriptorLocalScriptwill cause an error.Instead, when creating a custom chat system, or a system that needs access to the chat, you can use the
Chatservice'sChat.Chatfunction instead.CreateHumanoidModelFromDescriptionAsync
(description: HumanoidDescription, rigType: HumanoidRigType, assetTypeVerification: AssetTypeVerification = Default) → ModelYieldsReturns a characterModelequipped with everything specified in the passed inHumanoidDescription. IfHumanoidDescription.UseAvatarSettingsis set to true, Avatar Settings in the experience will be applied to the returned model.Returns a character
Modelequipped with everything specified in the passed inHumanoidDescription, and is R6 or R15 as specified byrigType.CreateHumanoidModelFromUserIdAsync
(userId: User) → ModelYieldsReturns a character Model set-up with everything equipped to match the avatar of the user specified by the passed in userId.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.
GetBanHistoryAsync
(userId: User) → BanHistoryPagesYieldsRetrieves the ban and unban history of any user within the experience's universe. This method is enabled and disabled by thePlayers.BanningEnabledproperty, which you can toggle in Studio.Retrieves the ban and unban history of any user within the experience's universe. This method returns a
BanHistoryPagesinstance that inherits fromPages. This method is enabled and disabled by thePlayers.BanningEnabledproperty, which you can toggle in Studio.This function call will only succeed on production 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.
GetCharacterAppearanceInfoAsync
(userId: User) → DictionaryYieldsReturns information about the character appearance of a given user.This function returns information about a player's avatar 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 useInsertService.LoadAssetto load the assets that are used in the player's avatar. The structure of the returned dictionary is as follows:Assets Sub-Table
The
assetstable is an array of tables containing the following keys that describe the assets currently equipped by the player:Scales Sub-Table
The
scalestable has the following keys, each a number corresponding to oneHumanoidscaling property:bodyType,head,height,proportion,depth,width.Body Colors Sub-Table
The
bodyColorstable has the following keys, each a number corresponding to aBrickColorID number which can be used withDatatype.BrickColor.new(id):leftArmColorId,torsoColorId,rightArmColorId,headColorId,leftLegColorId,rightLegColorId.GetFriendsAsync
(userId: User) → FriendPagesYieldsReturns aFriendPagesobject which contains information for all of the given player's friends.The GetFriendsAsync
Playersfunction returns aFriendPagesobject which contains information for all of the given user's friends. The items within theFriendPagesobject are tables with the following fields:See the code samples for an easy way to iterate over all a player's friends.
GetHumanoidDescriptionFromOutfitIdAsync
(outfitId: int64) → HumanoidDescriptionYieldsReturns the HumanoidDescription for a specified outfit, which will be set with the parts/colors/Animations etc of the outfit.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.
GetHumanoidDescriptionFromUserIdAsync
(userId: User) → HumanoidDescriptionYieldsReturns a HumanoidDescription which specifies everything equipped for the avatar of the user specified by the passed in userId.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.
GetNameFromUserIdAsync
(userId: User) → stringYieldsSends a query to the Roblox website for the username of an account with a givenUserId.The GetNameFromUserIdAsync
Playersfunction will send a query to the Roblox website asking what the username is of the account with the givenUserId.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
LuaGlobals.pcall. In addition, you can manually cache results to make future calls with the same UserId fast. See the code samples to learn more.GetPlayerByUserId
(userId: User) → PlayerReturns thePlayerwith the givenUserIdif they are in-experience.This function searches each
PlayerinPlayersfor one whosePlayer.UserIdmatches the givenuserId. If such a player does not exist, it returnsnil.This method is useful in finding the purchaser of a developer product using
MarketplaceService.ProcessReceiptwhich provides a table that includes the purchaser'sUserIdand not a reference to thePlayerobject itself. Most experiences will require a reference to the player in order to grant products.GetPlayerFromCharacter
(character: Model) → PlayerReturns thePlayerwhosePlayer.Charactermatches the given instance, ornilif one cannot be found.This function returns the
Playerassociated with the givenPlayer.Character, ornilif 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 endThis method is often used when some event in player's character fires (such as their
Humanoiddying). 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.GetPlayers
() → List<Player>Returns a table of all presently connectedPlayerobjects.This method returns a table of all presently connected
Playerobjects. It functions the same wayInstance.GetChildrenwould except that it only returnsPlayerobjects found underPlayers. When used with aforloop, it is useful for iterating over all players in an experience.local Players = game:GetService("Players") for _, player in Players:GetPlayers() do print(player.Name) endScripts that connect to
Players.PlayerAddedare often trying to process every Player that connects to the experience. This method is useful for iterating over already-connected players that wouldn't firePlayerAdded. 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)GetProfileConfigurationFromUserIdAsync
(userId: User) → ProfileConfigurationYieldsReturns the profile configuration of a user as a dictionary.Returns the profile configuration of the user specified by the given
Player.UserIdas a dictionary. The dictionary can include aBackgroundAssetIdfield for the user's profile background asset ID and aFrameAssetIdfield for the user's profile frame image asset ID.Can only be called from the server and is throttled to a limited number of requests per minute.
GetUserIdFromNameAsync
(userName: string) → int64YieldsSends a query to the Roblox website for theuserIdof an account with a given username.This function will send a query to the Roblox website asking what the
Player.UserIdis of the account with the givenPlayername.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
LuaGlobals.pcall. In addition, you can manually cache results to quickly make future calls with the same username. See the code samples to learn more.GetUserThumbnailAsync
(userId: User, thumbnailType: ThumbnailType, thumbnailSize: ThumbnailSize) → TupleYieldsReturns 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.This function returns the content URL of an image of a player's avatar given their
UserId, the desired image size as aThumbnailSizeenum, and the desired type as aThumbnailTypeenum. It also returns a boolean describing if the image is ready to use.Most often, this method is used with
ImageLabel.ImageorDecal.Textureto display user avatar pictures in an experience.SetChatStyle
(style: ChatStyle = Classic) → ()PluginSets whether BubbleChat and ClassicChat are being used, and tells TeamChat andChatwhat to do.This function sets whether BubbleChat and ClassicChat are being used, and tells TeamChat and Chat what to do using the
ChatStyleenum. Since this item is protected, attempting to use it in aScriptorLocalScriptwill cause an error.This function is used internally when the chat mode is set by the experience.
TeamChat
(message: string) → ()PluginMakes the local player chat the given message, which will only be viewable by users on the same team.This function makes the
Players.LocalPlayerchat the given message, which will only be viewable by users on the same team. Since this item is protected, attempting to use it in aScriptorLocalScriptwill cause an error.This function is used internally when the
Players.LocalPlayersends a message to their team.UnbanAsync
(config: Dictionary) → ()YieldsUnbans players banned fromPlayers.BanAsyncor the User Restrictions Open Cloud API. This method is enabled and disabled by thePlayers.BanningEnabledproperty, which you can toggle in Studio.Unbans players banned from
Players.BanAsyncor the User Restrictions Open Cloud API. This method is enabled and disabled by thePlayers.BanningEnabledproperty, which you can toggle in Studio.Like
Players.BanAsync, this method takes in aconfigdictionary 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
ApplyToUniversescope. For example, an unban withApplyToUniverseset totruewill not invalidate a previous ban withApplyToUniverseset tofalse. In other words, a universe level unban will not invalidate a place level ban. The opposite also holds true.For the case where a user's device may be blocked by a ban where
ApplyDeviceBlockwas set totrue, an unban applied by this method will override the device block for the unbanned player. Please note that unbanning a user through any other method, such as the Open Cloud API or the Creator Hub, will not lift the device block.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 includefailure for UserId {}if it is an HTTP error. It is undefined behavior if you pass in both valid and invalid UserIds, i.e. aUserIdthat 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 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 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.
Events 4
PlayerAdded
Players.PlayerAdded:Connect(function(player))Fires when a player enters the experience.This event fires when a player enters the experience, such as loading the player's saved
GlobalDataStoredata.This can be used alongside the
Players.PlayerRemovingevent, which fires when a player is about to leave the experience. For instance, if you would like print a message every time a new player joins or leaves:local Players = game:GetService("Players") Players.PlayerAdded:Connect(function(player) print(player.Name .. " joined the experience!") end) Players.PlayerRemoving:Connect(function(player, reason) print(player.Name .. " left the experience! Reason: " .. tostring(exitReason)) end)If you want to track when a player's character is added or removed from the experience, such as when a player respawns or dies, you can use the
Player.CharacterAddedandPlayer.CharacterRemovingfunctions.Note that this event does not work as expected in a solo playtest 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 experience after a player enters, create anonPlayerAdded()function that you can call to handle a player's entrance.PlayerMembershipChanged
Players.PlayerMembershipChanged:Connect(function(player))Fires when the experience server recognizes that a player's membership has changed.This event fires when the experience 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 experience 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 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 PremiumMarketplaceService.PromptPremiumPurchaseFinished, fires when the Premium purchase UI closes
PlayerRemoving
Players.PlayerRemoving:Connect(function(player, reason))Fires when a player is about to leave the experience.This event fires right before a
Playerleaves the experience, beforeChildRemovedfires onPlayers, and behaves somewhat similarly toInstance.DescendantRemoving. Since it fires before the actual removal of aPlayer, this event is useful for storing player data using aGlobalDataStore.This can be used alongside the
Player.PlayerAddedevent, which fires when a player joins the experience. For instance, to print a message every time a new player joins or leaves:local Players = game:GetService("Players") Players.PlayerAdded:Connect(function(player) print(player.Name .. " joined the experience!") end) Players.PlayerRemoving:Connect(function(player, exitReason) print(player.Name .. " left the experience! - Reason: " .. tostring(exitReason)) end)If you want to track when a player's character is added or removed from the experience, such as when a player respawns or dies, you can use the
Player.CharacterAddedandPlayer.CharacterRemovingfunctions.UserSubscriptionStatusChanged
Players.UserSubscriptionStatusChanged:Connect(function(user, subscriptionId))Fires when the experience server recognizes that the user's status for a certain subscription has changed.This event fires when the experience 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 experience 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 server updates their subscription status and triggers this event.
Note that only server scripts receive this event.
Players also has every member of Instance. Deprecated and Roblox-only members are hidden.
Reference text from the Roblox Creator Documentation, licensed CC BY 4.0, reorganized by rbxtoolshub.com · Studio 0.743.0.7431133.