A Player object is a client that is currently connected. These objects areadded to the Players service when a new player connects, then removedwhen they eventually disconnect from the server.
The Instance.Name property reflects the player's username. When savinginformation about a player, you should use their Player.UserId sinceit is possible that a player can change their username.
There are several similar methods in the Players service for workingwith Player objects. Use these over their respective Instance methods:
You can get a table of current Player objects usingPlayers:GetPlayers(); again, use this instead ofInstance:GetChildren().
To detect the addition of Player objects, it is recommended to use thePlayers.PlayerAdded event (instead of Instance.ChildAdded onthe Players service).
Similarly, you can detect the removal of Player objects usingPlayers.PlayerRemoving, which fires just before the Player isremoved (instead of Instance.ChildRemoved which fires after). Thisis important if you are saving information about the player that might beremoved or cleaned up on-removal.
Code Samples
Leaderstats
local Players = game:GetService("Players")
local function onPlayerAdded(player)
-- Create a container for leaderstats
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
-- Create one leaderstat value
local vScore = Instance.new("IntValue")
vScore.Name = "Score"
vScore.Value = 0
vScore.Parent = leaderstats
-- Add to player (displaying it)
leaderstats.Parent = player
end
Players.PlayerAdded:Connect(onPlayerAdded)
Summary
Properties
AccountAge:number
Read Only
Not Replicated
Read Parallel
Describes the player's account age in days.
AutoJumpEnabled:bool
Read Parallel
Determines whether the character of a player using a mobile device willautomatically jump upon hitting an obstacle.
CameraMaxZoomDistance:number
Read Parallel
The maximum distance the player's camera is allowed to zoom out.
CameraMinZoomDistance:number
Read Parallel
The minimum distance the player's camera is allowed to zoom in.
CameraMode:Enum.CameraMode
Read Parallel
Changes the camera's mode to either first or third person.
CanLoadCharacterAppearance:bool
Read Parallel
Determines whether the character's appearance will be loaded when theplayer spawns. If false, the player will spawn with a default appearance.
Character:Model
Read Parallel
A Model controlled by the player that contains a Humanoid,body parts, scripts, and other objects.
CharacterAppearanceId:number
Read Parallel
Determines the user ID of the account whose character appearance is usedfor a player's character.
DevCameraOcclusionMode:Enum.DevCameraOcclusionMode
Read Parallel
Sets how the default camera handles objects between the camera and theplayer.
DevComputerCameraMode:Enum.DevComputerCameraMovementMode
Read Parallel
Determines player's camera movement mode when using a desktop version ofRoblox.
DevComputerMovementMode:Enum.DevComputerMovementMode
Read Parallel
Determines player's character movement mode when using a desktop versionof Roblox.
DevEnableMouseLock:bool
Read Parallel
Determines if the player can toggle mouse lock.
DevTouchCameraMode:Enum.DevTouchCameraMovementMode
Read Parallel
Determines player's camera movement mode when using a touch device.
DevTouchMovementMode:Enum.DevTouchMovementMode
Read Parallel
Determines player's character movement mode when using a touch device.
DisplayName:string
Read Parallel
The DisplayName of the UserId associated with the Player.
FollowUserId:number
Read Only
Not Replicated
Read Parallel
Describes the user ID of the player who was followed into a game by aplayer.
GameplayPaused:bool
Read Parallel
Whether player client-side gameplay is currently paused.
HasVerifiedBadge:bool
Read Parallel
Indicates if a player has a Verified Badge.
HealthDisplayDistance:number
Read Parallel
Sets the distance at which this player will see other Humanoid's healthbars. If set to 0, the health bars will not be displayed.
LocaleId:string
Hidden
Read Only
Not Replicated
Read Parallel
This property shows the locale id that the local player has set for theirRoblox account.
MembershipType:Enum.MembershipType
Read Only
Not Replicated
Read Parallel
Describes the account's membership type.
NameDisplayDistance:number
Read Parallel
Sets the distance at which this player will see other Humanoid's names. Ifset to 0, names are hidden.
Neutral:bool
Read Parallel
Determines whether the player is on a specific team.
ReplicationFocus:Instance
Read Parallel
Sets the part to focus replication around.
RespawnLocation:SpawnLocation
Read Parallel
If set, the player will respawn at the given SpawnLocation.
Team:Team
Not Replicated
Read Parallel
Determines the Team with which a Player is associated.
TeamColor:BrickColor
Read Parallel
Determines the Team with which a Player is associated.
UserId:number
Read Parallel
A unique identifying integer assigned to all user accounts.
Methods
ClearCharacterAppearance():void
Removes all accessories and other character appearance objects from aplayer's Character.
Returns the distance between the character's head and the given Vector3point. Returns 0 if the player has no character.
GetJoinData():Dictionary
Returns a dictionary containing information describing how thePlayer joins the experience.
GetMouse():Mouse
Returns the mouse being used by the client.
GetNetworkPing():number
Write Parallel
Returns the isolated network latency in seconds.
HasAppearanceLoaded():bool
Returns whether or not the appearance of the player's character hasloaded.
IsVerified():bool
Returns whether the player is verified with concrete, real-world signals.
Kick(message : string):void
Forcibly disconnect a player from the game, optionally providing amessage.
Causes the player's character to walk in the given direction untilstopped, or interrupted by the player (by using their controls).
SetAccountAge(accountAge : number):void
Plugin Security
Sets the AccountAge of the player.
SetSuperSafeChat(value : bool):void
Plugin Security
Sets whether or not the player sees filtered chats, rather than normalchats.
Returns a dictionary of online friends.
Returns the player's rank in the group as an integer between 0 and 255,where 0 is a non-member and 255 is the group's owner.
Returns the player's role in the group as a string, or "Guest" if theplayer isn't part of the group.
Checks whether a player is a friend of the user with the givenPlayer.UserId.
Checks whether a player is a member of a group with the given ID.
LoadCharacter():void
Yields
Creates a new character for the player, removing the old one. Also clearsthe player's Backpack and PlayerGui.
LoadCharacterWithHumanoidDescription(humanoidDescription : HumanoidDescription):void
Yields
Spawns an avatar so it has everything equipped in the passed inHumanoidDescription.
Requests that the server stream to the player around the specifiedlocation.
Events
CharacterAdded(character : Model):RBXScriptSignal
Fired when a player's character spawns or respawns.
CharacterAppearanceLoaded(character : Model):RBXScriptSignal
Fires when the full appearance of a Player.Character has beeninserted.
CharacterRemoving(character : Model):RBXScriptSignal
Fired right before a player's character is removed.
Chatted(message : string,recipient : Player):RBXScriptSignal
Fires when a player chats in-game using Roblox's provided chat bar.
Idled(time : number):RBXScriptSignal
This event fires approximately two minutes after the game engineclassifies the player as idle. Time is the number ofseconds that have elapsed since that point.
OnTeleport(teleportState : Enum.TeleportState,placeId : number,spawnName : string):RBXScriptSignal
Fired when the TeleportState of a player changes.
Properties
AccountAge
Read Only Not Replicated Read Parallel
The AccountAge is a Player property that describes how long ago aplayer's account was registered in days. It is set using thePlayer:SetAccountAge() function, which cannot be accessed byscripts.
This property is useful for conditionally showing new Roblox playerscontent such as tutorials.
Code Samples
Account Age Mark
local Players = game:GetService("Players")
local MAX_AGE_NEW_PLAYER = 7 -- one week
local MIN_AGE_VETERAN = 365 -- one year
-- This function marks a part with text using a BillboardGui
local function mark(part, text)
local bbgui = Instance.new("BillboardGui")
bbgui.AlwaysOnTop = true
bbgui.StudsOffsetWorldSpace = Vector3.new(0, 2, 0)
bbgui.Size = UDim2.new(0, 200, 0, 50)
local textLabel = Instance.new("TextLabel")
textLabel.Size = UDim2.new(1, 0, 1, 0) -- Fill parent
textLabel.Text = text
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.BackgroundTransparency = 1
textLabel.Parent = bbgui
-- Add to part
bbgui.Parent = part
bbgui.Adornee = part
end
local function onPlayerSpawned(player, character)
local head = character:WaitForChild("Head")
if player.AccountAge >= MIN_AGE_VETERAN then
mark(head, "Veteran Player")
elseif player.AccountAge <= MAX_AGE_NEW_PLAYER then
mark(head, "New Player")
else
mark(head, "Regular Player")
end
end
local function onPlayerAdded(player)
-- Listen for this player spawning
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
AutoJumpEnabled
Read Parallel
The AutoJumpEnabled property determines whether thePlayer.Character of a Player using a mobile device willautomatically jump when they hit an obstacle. This can make levels morenavigable while on a mobile device.
When the player joins the game, the StarterPlayer.AutoJumpEnabledvalue determines the initial state of this property. Then, this propertydetermines the value of the Humanoid.AutoJumpEnabled property ofthe Player.Character on spawn. In other words, it is possible toset the auto-jump behavior on a per-character, per-player and per-gamebasis using these three properties.
Code Samples
Auto-Jump Toggle
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local button = script.Parent
local function update()
-- Update button text
if player.AutoJumpEnabled then
button.Text = "Auto-Jump is ON"
else
button.Text = "Auto-Jump is OFF"
end
-- Reflect the property in the player's character, if they have one
if player.Character then
local human = player.Character:FindFirstChild("Humanoid")
if human then
human.AutoJumpEnabled = player.AutoJumpEnabled
end
end
end
local function onActivated()
-- Toggle auto-jump
player.AutoJumpEnabled = not player.AutoJumpEnabled
-- Update everything else
update()
end
button.Activated:Connect(onActivated)
update()
CameraMaxZoomDistance
Read Parallel
The CameraMaxZoomDistance Player property sets the maximumdistance in studs the camera can be from the character with the defaultcameras.
In other words, it controls the maximum distance the player's camera isallowed to zoom out.
The default value of this property is set byStarterPlayer.CameraMaxZoomDistance. If this value is set to alower value than Player.CameraMinZoomDistance, it will beincreased to CameraMinZoomDistance.
Code Samples
Setting Camera Zoom Distance
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75
CameraMinZoomDistance
Read Parallel
The CameraMinZoonDistance Player property sets the minimumdistance in studs the camera can be from the character with the defaultcameras.
In other words, it controls the minimum distance the player's camera isallowed to zoom in.
The default value of this property is set byStarterPlayer.CameraMinZoomDistance. If this value is set to ahigher value than Player.CameraMaxZoomDistance it will bedecreased to CameraMaxZoomDistance.
Code Samples
Setting Camera Zoom Distance
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75
CameraMode
Read Parallel
The CameraMode property sets the player's camera mode, defaulting tothird person.
Third Person
In the default third person mode (Enum.CameraMode.Classic), thecharacter can be seen in the camera. While in this mode, the defaultbehavior is:
Players can right-click and drag (mouse), tap and drag (mobile), use thesecondary thumbstick (gamepad), or press the left/right arrows(keyboard) to rotate the camera around their character.
When a player moves their character, it faces in the correspondingmovement direction.
Players can zoom in and out freely, even to first person on full zoomin.
First Person
In first person mode (Enum.CameraMode.LockFirstPerson), the player'scamera is zoomed all the way in. Unless there is a visible GUI presentwith the GuiButton.Modal property set to true, moving the mouse,tap-dragging on mobile, or using the secondary thumbstick on a gamepadwill rotate the camera around the character.
Code Samples
Playing in First Person
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMode = Enum.CameraMode.LockFirstPerson
CanLoadCharacterAppearance
Read Parallel
The CanLoadCharacterAppearance Player property determines whetherthe character's appearance will be loaded when the player spawns. Thedefault value of this property is set byStarterPlayer.LoadPlayerAppearance.
If true, the character will load the appearance of the playercorresponding to the player's Player.CharacterAppearanceId.
If false, the player will spawn with a default appearance - a greycharacter model without any hats, shirts, pants, etc.
Attempting to set the property after the character has spawned will notchange the character, you must call Player:LoadCharacter() to loadthe new appearance.
Code Samples
Disabling a Player's Appearance
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CanLoadCharacterAppearance = false
Character
Read Parallel
The Character property contains a reference to a Modelcontaining a Humanoid, body parts, scripts, and other objectsrequired for simulating the player's avatar in-experience. The model isparented to the Workspace but it may be moved. It is automaticallyloaded when Players.CharacterAutoLoads is true and it can bemanually loaded otherwise using Player:LoadCharacter().
Initially this property is nil and it is set when the player's characterfirst spawns. Use the Player.CharacterAdded event to detect when aplayer's character properly loads, and thePlayer.CharacterRemoving event to detect when the character isabout to despawn. Avoid using Instance:GetPropertyChangedSignal()on this property.
Note that LocalScripts that are cloned fromStarterGui or StarterPack into a player'sPlayerGui or Backpack respectively are often run beforethe old character model is replaced, so Player.Character may referto the old model whose Parent property is nil.Therefore, in a LocalScript under StarterGui orStarterPack, it is advisable to make sure the parent ofCharacter is not nil before using it, for example:
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character
if not character or character.Parent == nil then
character = player.CharacterAdded:Wait()
end
CharacterAppearanceId
Read Parallel
This property determines the user ID of the account whose characterappearance is used for a player's Player.Character. By default,this property is the Player.UserId, which uses the player's avataras they have created it on the Roblox website.
Changing this property to the user ID of another account will cause theplayer to spawn with that account's appearance (hats, shirt, pants, etc).
Games can also toggle whether or not a player's character appearance isloaded in game by changing theStarterPlayer.LoadCharacterAppearance property.
Code Samples
Disguise Command
local Players = game:GetService("Players")
local disguiseCommand = "/disguise "
local function onPlayerChatted(player, message)
if message:sub(1, disguiseCommand:len()):lower() == disguiseCommand:lower() then
local input = message:sub(disguiseCommand:len() + 1)
local id = tonumber(input)
if not id then -- Number failed to parse, maybe they typed a username instead
pcall(function() -- This call can fail sometimes!
id = Players:GetUserIdFromNameAsync(input) -- Fetch ID from name
end)
See AlsoCan someone please explain Mouse.Hit.pAvatar Items | Documentation - Roblox Creator HubEverything You Need to Know About Robux - KidasIntroduction to Scripting | Documentation - Roblox Creator Hubend
if id then
-- Set character appearance then respawn
player.CharacterAppearanceId = id
player:LoadCharacter()
else
-- We couldn't get an ID from their input
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
DevCameraOcclusionMode
Read Parallel
Defines how the default camera scripts handle objects between the cameraand the camera subject. Set byStarterPlayer.DevCameraOcclusionMode and can't be changed forindividual players.
The default value is Zoom (0). SeeEnum.DevCameraOcclusionMode for a list of available modes.
DevComputerCameraMode
Read Parallel
The DevComputerCameraMode property determines the manner in which a playermoves their camera when using a device with a mouse and keyboard. SeeEnum.DevComputerCameraMovementMode for a description of each cameracontrol mode available. This property cannot be set using aLocalScript (it must be set on the server using a Script).
The default value of this property is determined byStarterPlayer.DevComputerCameraMovementMode.
The word "Computer" in this property name refers tonon-TouchEnabled,non-GamepadEnabled devices.
When set to UserChoice, a player can choose between any control mode(except Scriptable) in the Roblox game settings. In general, it's agood idea to allow players to choose their control mode to maximizeaccessibility.
It's possible to create a custom control scheme by setting this propertyto Scriptable.
This property doesn't affect players using a touch enabled device. SeePlayer.DevTouchCameraMode instead.
Code Samples
Setting a Player's Camera Movement Mode (Desktop)
local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- Set the player's camera movement mode on computers to classic
player.DevComputerCameraMode = Enum.DevComputerCameraMovementMode.Classic
DevComputerMovementMode
Read Parallel
The DevComputerMovementMode property determines the manner in which aplayer moves their character when using a device with a mouse andkeyboard. See Enum.DevComputerMovementMode for a description of eachmovement control mode available. This property cannot be set using aLocalScript (it must be set on the server using a Script).
The default value of this property is determined byStarterPlayer.DevComputerMovementMode.
The word "Computer" in this property name refers tonon-TouchEnabled devices.
When set to UserChoice, a player can choose between any control mode(except Scriptable) in the Roblox game settings. In general, it is agood idea to allow players to choose their control mode to maximizeaccessibility.
It's possible to create a custom control scheme by setting this propertyto Scriptable.
This property doesn't affect players using a touch-enabled device. SeePlayer.DevTouchMovementMode instead.
Code Samples
Setting a Player's Movement Mode (Desktop)
local Players = game:GetService("Players")
game.Players.PlayerAdded:Connect(function(player)
-- Set the player's movement mode on mobile devices to a dynamic thumbstick
player.DevComputerMovementMode = Enum.DevComputerMovementMode.DynamicThumbstick
end)
DevEnableMouseLock
Read Parallel
This property determines if a player is able to toggle Mouse lockby pressing Shift. A player can disable the mouse lock switch inRoblox's game settings. By default, this property is set to the value ofStarterPlayer.EnableMouseLockOption. This can be set server-sideduring run-time by using a Script. It can not be set client-side.
When mouse lock is enabled, the player's cursor is locked to the center ofthe screen. Moving the mouse will orbit the camera around the player'scharacter, and the character will face the samedirection as the camera. It also offsets the camera viewjust over the right shoulder of the player's character.
Note that shift-lock related APIs are in the process of being deprecated,so it's recommended to use UserInputService.MouseBehavior insteadto lock the mouse.
Code Samples
Toggling Mouse Lock Ability
local Players = game:GetService("Players")
local function toggleMouseLock(player)
player.DevEnableMouseLock = not player.DevEnableMouseLock
if player.DevEnableMouseLock then
print("Mouse lock is available")
else
print("Mouse lock is not available")
end
end
local function onPlayerChatted(player, message, _recipient)
if message == "mouselock" then
toggleMouseLock(player)
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
DevTouchCameraMode
Read Parallel
The DevTouchCameraMode property determines the manner in which a playermoves their camera when using aTouchEnabled device. SeeEnum.DevTouchCameraMovementMode for a description of each camera controlmode available. This property cannot be set using a LocalScript(it must be set on the server using a Script).
The default value of this property is determined byStarterPlayer.DevTouchCameraMovementMode.
When set to UserChoice, a player can choose between any control mode(except Scriptable) in the Roblox game settings. In general, it is agood idea to allow players to choose their control mode to maximizeaccessibility.
It's possible to create a custom control scheme by setting this propertyto Scriptable.
This property doesn't affect players who aren't using a touch-enableddevice. See Player.DevComputerCameraMovementMode instead.
Code Samples
Setting a Player's Camera Movement Mode (Touch)
local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- Set the player's camera movement mode on mobile devices to classic
player.DevTouchCameraMovementMode = Enum.DevTouchCameraMovementMode.Classic
DevTouchMovementMode
Read Parallel
The DevTouchMovementMode property determines the manner in which a playermoves their character when using aTouchEnabled device. SeeEnum.DevTouchMovementMode for a description of each movement controlmode available. This property cannot be set using a LocalScript(it must be set on the server using a Script).
The default value of this property is determined byStarterPlayer.DevTouchMovementMode.
When set to UserChoice, a player can choose between any control mode(except Scriptable) in the Roblox game settings. In general, it's agood idea to allow players to choose their control mode to maximizeaccessibility.
It's possible to create a custom control scheme by setting this propertyto Scriptable.
This property doesn't affect players who aren't using a touch-enableddevice. See Player.DevComputerMovementMode instead.
Code Samples
Setting a Player's Movement Mode (Touch)
local Players = game:GetService("Players")
game.Players.PlayerAdded:Connect(function(player)
-- Set the player's movement mode on mobile devices to a dynamic thumbstick
player.DevTouchMovementMode = Enum.DevTouchMovementMode.DynamicThumbstick
end)
DisplayName
Read Parallel
The DisplayName is a Player property that contains the displayname of the authenticated user associated with the Player object.Unlike usernames, display names are non-unique names a player displays toothers. If the Roblox user has not chosen one, the property will read thesame as the Name property.
Note:
Since display names are non-unique, it's possible for two players in asingle instance to have identical names. If you need a globally uniqueidentifier for a player, use Player.UserId (which is static) orPlayer.Name (which is the current Username) instead.
Characters generated with Player.LoadCharacter or by the Robloxengine will have their Humanoid.DisplayName property assigned tothe Player.DisplayName property.
Display names may have unicode characters in the string. SeeUTF-8 for more information on how to work with stringswith unicode characters.
FollowUserId
Read Only Not Replicated Read Parallel
The FollowUserId is a Player property that contains thePlayer.UserId of the user that a player followed into the game. Ifthe player did not follow anyone into the game, this property will be 0.This property is useful for alerting players who have been followed byanother player into the game.
You can get the name of the player followed using this user ID and thePlayers:GetNameFromUserIdAsync() function.
Code Samples
Followed Alert
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local function onPlayerAdded(newPlayer)
if newPlayer.FollowUserId == player.UserId then
local hint = Instance.new("Hint")
hint.Parent = player:WaitForChild("PlayerGui")
hint.Text = "You were followed to this game by " .. newPlayer.Name .. "!"
task.delay(3, function()
if hint then
hint:Destroy()
end
end)
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
GameplayPaused
Read Parallel Not Accessible Security
The GameplayPaused property indicates if the player is currently in apause state in a place withStreamingEnabled activated. It is seton the client but replicated to the server. To determine the pause status,you can utilize this property.
See also:
Workspace.StreamingEnabled which controls whether contentstreaming is enabled
Workspace.StreamingIntegrityMode andEnum.StreamingIntegrityMode for more details on when gameplay ispaused.
HasVerifiedBadge
Read Parallel
The HasVerifiedBadge Player property indicates if the player has aVerified Badge.
HealthDisplayDistance
Read Parallel
The HealthDisplayDistance Player property sets the distance instuds at which this player will see other Humanoid health bars. Ifset to 0, the health bars will not be displayed. This property is set toStarterPlayer.HealthDisplayDistance by default.
If a Humanoid's health bar is visible, you can set the display type usingHumanoid.DisplayDistanceType.
Code Samples
Hiding Player Health and Names
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0
LocaleId
Hidden Read Only Not Replicated Read Parallel
The LocaleId Player property shows the locale id that the localplayer has set for their Roblox account. It holds a string with the twoletter code (for example, "en-us") for the locale.
This can be used to determine the geographic demographic of your game'splayer base.
This property allows access to the player's locale from the server. It issimilar to the LocalizationService.RobloxLocaleId property.
Code Samples
Checking a Player's Locale
local Players = game:GetService("Players")
local player = Players.LocalPlayer
print(player.LocaleId)
MembershipType
Read Only Not Replicated Read Parallel
The MembershipType Player property can be used to determine themembership type of the player. It holds a Enum.MembershipType enum ofthe account's membership type.
This property can only be read from to determine membership (it cannot beset to another membership type). The property can only be changed viaClass.CoreScript|CoreScripts using Player:SetMembershipType() -which are not accessible.
Code Samples
Check Player Membership Status
local Players = game:GetService("Players")
local player = Players.LocalPlayer
if player.MembershipType == Enum.MembershipType.Premium then
-- Take some action specifically for Premium members
end
NameDisplayDistance
Read Parallel
The NameDisplayDistance StarterPlayer property sets the distancein studs at which this player will see other Humanoid names. Ifthe property is set to 0, names are hidden. This property is set toStarterPlayer.NameDisplayDistance by default.
If a Humanoid's health bar is visible, you can set the display type usingHumanoid.DisplayDistanceType.
Code Samples
Hiding Player Health and Names
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0
Neutral
Read Parallel
The Neutral property determines whether the player is on a specific team.
When true, the player is not on a specific team. This also means thatthe Player.Team property will be nil and thePlayer.TeamColor will be white.
When false, the player is on a specific team. The Player.Teamproperty will correspond to the Team that the player is on, aswill the Player.TeamColor.
Code Samples
Checking if a Player is Neutral
local Players = game:GetService("Players")
local player = Players.LocalPlayer
if player.Neutral then
print("Player is neutral!")
else
print("Player is not neutral!")
end
ReplicationFocus
Read Parallel
The ReplicationFocus Player property sets the part to focusreplication around a Player. Different Roblox systems that communicateover the network (such as physics, streaming, etc) replicate at differentrates depending on how close objects are to the replication focus.
When this property is nil, it reverts to its default behavior which is totreat the local player's character's PrimaryPartas the replication focus.
This property should only be set on the server with a Script, nota LocalScript. Note that this property does not change or updatenetwork ownership of parts.
Code Samples
Setting a Player's Replication Focus
local Players = game:GetService("Players")
local PLAYER_NAME = "polarpanda16"
local player = Players:WaitForChild(PLAYER_NAME)
local part = Instance.new("Part")
part.Parent = workspace
part.Name = "ReplicationFocusPart"
part.Anchored = true
player.ReplicationFocus = part
RespawnLocation
Read Parallel
If set, the player will respawn at the given SpawnLocation. Thisproperty can only be set through Lua and must contain a reference to avalid SpawnLocation, which must meet the following criteria:
Descendant of Workspace
SpawnLocation.TeamColor is set to the Player.TeamColoror SpawnLocation.Neutral is set to true
If RespawnLocation is not set to a valid SpawnLocation then thedefault spawning logic will apply. For more information on this see thepage for SpawnLocation.
Alternatives to RespawnLocation
A Player will spawn from SpawnLocationsbelonging to their team. In some cases it may be simpler to change theplayer's Player.Team instead.
Implement your own custom spawn logic using PVInstance:PivotTo()to manually move the Player.Character.
Code Samples
Change Spawn on Touch
local Players = game:GetService("Players")
local function addSpawn(spawnLocation)
-- listen for the spawn being touched
spawnLocation.Touched:Connect(function(hit)
local character = hit:FindFirstAncestorOfClass("Model")
if character then
local player = Players:GetPlayerFromCharacter(character)
if player and player.RespawnLocation ~= spawnLocation then
local humanoid = character:FindFirstChildOfClass("Humanoid")
-- make sure the character isn't dead
if humanoid and humanoid:GetState() ~= Enum.HumanoidStateType.Dead then
print("spawn set")
player.RespawnLocation = spawnLocation
end
end
end
end)
end
local firstSpawn
-- look through the workspace for spawns
for _, descendant in pairs(workspace:GetDescendants()) do
if descendant:IsA("SpawnLocation") then
if descendant.Name == "FirstSpawn" then
firstSpawn = descendant
end
addSpawn(descendant)
end
end
local function playerAdded(player)
player.RespawnLocation = firstSpawn
end
-- listen for new players
Players.PlayerAdded:Connect(playerAdded)
-- go through existing players
for _, player in pairs(Players:GetPlayers()) do
playerAdded(player)
end
Team
Not Replicated Read Parallel
The Team property is a reference to a Team object within theTeams service. It determines the team the player is on; if thePlayer isn't on a team or has an invalid Player.TeamColor,this property is nil. When this property is set, the player has joined theTeam and the Team.PlayerAdded event fires on theassociated team. Similarly, Team.PlayerRemoved fires when theproperty is unset from a certain Team.
Code Samples
Playing/Spectating Teams
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
local teamPlaying = Teams.Playing
local teamSpectators = Teams.Spectating
local playCommand = "/play"
local function play(player)
player.Team = teamPlaying
player.TeamColor = teamPlaying.TeamColor
-- Respawn the player (moves them to spawn location)
player:LoadCharacter()
end
local function onPlayerDied(player, _character)
-- When someone dies, put them on the spectator team
player.Team = teamSpectators
end
local function onPlayerSpawned(player, character)
local human = character:WaitForChild("Humanoid")
human.Died:Connect(function()
onPlayerDied(player, character)
end)
end
local function onPlayerChatted(player, message)
if message:sub(1, playCommand:len()):lower() == playCommand then
play(player)
end
end
local function onPlayerAdded(player)
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
player.Chatted:Connect(function(message, _recipient)
onPlayerChatted(player, message)
end)
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Join Team Command
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
-- Command to choose a team (note the trailing space)
local joinCommand = "/jointeam "
local function findTeamByName(name)
-- First, check for the exact name of a team
if Teams:FindFirstChild(name) then
return Teams[name]
end
-- Let's check for case-insensitive partial matches, like "red" for "Red Robins"
for _, team in pairs(Teams:GetChildren()) do
if team.Name:sub(1, name:len()):lower() == name:lower() then
return team
end
end
-- If we get to this point, no team matched the one we were looking for :(
end
local function onPlayerChatted(player, message, _recipient)
-- Note: string.sub(message, ...) is the same as message:sub(...)
if message:sub(1, joinCommand:len()):lower() == joinCommand:lower() then
-- Matched "/JOINTEAM xyz" to our join command prefix "/jointeam "
local teamName = message:sub(joinCommand:len() + 1) -- Cut out the "xyz" from "/jointeam xyz"
local team = findTeamByName(teamName)
if team then
-- Set the team!
player.Team = team
player.Neutral = false
else
-- Tell the player that team could not be found :(
player.Team = nil
player.Neutral = true
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
TeamColor
Read Parallel
The TeamColor property determines which team a Player is associated withaccording to that Team's Team.TeamColor. Changing this propertywill change Player.Team according to whichever team has the sameBrickColor for their Team.TeamColor. If no Team objecthas the associated TeamColor, the player will not be associated with ateam.
It's often a better idea to set Player.Team to the respectiveTeam instead of using this property. Setting this property oftenleads to repetition of the same BrickColor value for a certain team acrossmany scripts; this is something you want to avoid when adhering to thedon't-repeat-yourself principle.
Code Samples
Playing/Spectating Teams
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
local teamPlaying = Teams.Playing
local teamSpectators = Teams.Spectating
local playCommand = "/play"
local function play(player)
player.Team = teamPlaying
player.TeamColor = teamPlaying.TeamColor
-- Respawn the player (moves them to spawn location)
player:LoadCharacter()
end
local function onPlayerDied(player, _character)
-- When someone dies, put them on the spectator team
player.Team = teamSpectators
end
local function onPlayerSpawned(player, character)
local human = character:WaitForChild("Humanoid")
human.Died:Connect(function()
onPlayerDied(player, character)
end)
end
local function onPlayerChatted(player, message)
if message:sub(1, playCommand:len()):lower() == playCommand then
play(player)
end
end
local function onPlayerAdded(player)
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
player.Chatted:Connect(function(message, _recipient)
onPlayerChatted(player, message)
end)
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
UserId
Read Parallel
The UserId is a Player property that contains a read-only integerthat uniquely and consistently identifies every user account onRoblox. Unlike the Instance.Name of a Player, which may changeaccording the user's present username, this value will never change forthe same account.
This property is essential when saving/loading player data usingGlobalDataStores. Use a player's UserId as thedata store key so that each player has a unique key.
Code Samples
Player.UserId
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print(player.UserId)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Players:GetPlayerByUserId
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
Met the Creator Badge
local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
local OWNER_ID = 212423 -- can use game.CreatorId for published places
local BADGE_ID = 1
local ownerInGame = false
local function playerAdded(newPlayer)
if newPlayer.UserId == OWNER_ID then
-- if new player is the owner, set ownerInGame to true and give everyone the badge
ownerInGame = true
for _, player in pairs(Players:GetPlayers()) do
-- don't award the owner
if player ~= newPlayer then
BadgeService:AwardBadge(player.UserId, BADGE_ID)
end
end
elseif ownerInGame then
-- if the owner is in the game, award the badge
BadgeService:AwardBadge(newPlayer.UserId, BADGE_ID)
end
end
local function playerRemoving(oldPlayer)
if oldPlayer.UserId == OWNER_ID then
ownerInGame = false
end
end
Players.PlayerAdded:Connect(playerAdded)
Players.PlayerRemoving:Connect(playerRemoving)
Data Store to Leaderboard
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local goldDataStore = DataStoreService:GetDataStore("Gold")
local STARTING_GOLD = 100
local function onPlayerAdded(player)
local playerKey = "Player_" .. player.UserId
local leaderstats = Instance.new("IntValue")
leaderstats.Name = "leaderstats"
local gold = Instance.new("IntValue")
gold.Name = "Gold"
gold.Parent = leaderstats
local success, result = pcall(function()
return goldDataStore:GetAsync(playerKey) or STARTING_GOLD
end)
if success then
gold.Value = result
else
-- Failed to retrieve data
warn(result)
end
leaderstats.Parent = player
end
Players.PlayerAdded:Connect(onPlayerAdded)
Methods
ClearCharacterAppearance
void
The ClearCharacterAppearance function removes all Accessory,Shirt, Pants, CharacterMesh, andBodyColors from the given player's Player.Character. Inaddition, it also removes the T-Shirt Decal on the player's torso.The character's body part colors and face will remain unchanged. Thismethod does nothing if the player does not have a Character.
It does not remove t-shirts, head meshes, or faces.
Returns
void
Code Samples
How to Clear a Character's Appearance
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local function onChildRemoved(child)
print(child.ClassName, "removed from character")
end
character.ChildRemoved:Connect(onChildRemoved)
player:ClearCharacterAppearance()
--> BodyColors removed from character
--> ShirtGraphic removed from character
--> Shirt removed from character
--> Pants removed from character
--> CharacterMesh removed from character
--> Hat removed from character
--> Shirt removed from character
DistanceFromCharacter
The DistanceFromCharacter Player function returns the distancebetween the character's head and the given Vector3 point. Itreturns 0 if the player has no Player.Character.
This is useful when determining the distance between a player and anotherobject or location in game.
If you would like to determine the distance between two non-playerinstances or positions, you can use the following:
local distance = (position1 - position2).magnitude
Parameters
point: Vector3
The location from which player's distance to is being measured.
Returns
The distance in studs between the player and the location.
Code Samples
Measuring the Distance Between a Player and a Position
local Players = game:GetService("Players")
for _, player in pairs(Players:GetPlayers()) do
print(player:DistanceFromCharacter(Vector3.new(0, 0, 0)))
end
GetJoinData
Returns a dictionary containing information describing how the Playerjoins the experience. The dictionary contains any of the following fields:
Key | Value Type | Description |
---|---|---|
SourceGameId | number | The DataModel.GameId of the experience the Player teleported from. Only present if the player teleports to the current experience and if a server calls the teleport function. |
SourcePlaceId | number | The DataModel.PlaceId of the place the Player teleported from. Only present if the player teleports to the current place and a server calls the teleport function. |
Members | array | An array containing the Player.UserId numbers of the users teleported alongside the Player. Only present if the player teleported as part of a group. |
TeleportData | variant | Reflects the teleportData specified in the original teleport. Useful for sharing information between servers the player teleports to. Only present if teleportData was specified and a server calls the teleport function. |
LaunchData | string | A string containing launch data specified in the URL the player clicks to join the experience. Only present if the URL contains launch data. |
GetJoinData and TeleportData
If a server initiates the Player's teleport, the dictionary that thismethod returns includes the player's teleport data. ThePlayer:GetJoinData() method can only be used to fetch teleportdata on the server. To fetch the data on the client, useTeleportService:GetLocalPlayerTeleportData().
Unlike TeleportService:GetLocalPlayerTeleportData(),Player:GetJoinData() only provides teleport data that meets thefollowing security criteria:
It's guaranteed to have been sent by a Roblox server in the past 48hours.
It's guaranteed to have been sent with this Player.
The SourcePlaceId and SourceGameId are guaranteed to be the placeand universe the data was sent from. This means you can verify theteleport data came from an approved place.
As this data is transmitted by the client, it can still potentially beabused by an exploiter. Sensitive data such as player currency should betransmitted via a secure solution likeMemory Stores.
LaunchData
Contains the string embedded in the launchData URL parameter that the userclicked to join the experience. Only available on the first join. If theuser teleports to another server, the data isn't included. If you need thedata after a teleport, forward it manually as teleport data. You can onlyinclude LaunchData in direct join URLs, not URLs to the experience's page.
LaunchData is a URL parameter that you can create by adding&launchData=abcd to a URL, where abcd is the data. Special characterssuch as spaces must be URL encoded using HttpService:UrlEncode()and are automatically decoded when the user joins the game. The decodedlaunch data can't exceed 200 bytes. You can store more complex data as aJSON string and decode it with HttpService:JSONDecode() on theserver.
This link joins the LaunchData sample place and starts the user in room 2:https://www.roblox.com/games/start?placeId=6900305353&launchData=%7B%22roomId%22%3A%202%7D
You can also make sure that this link works for users without Robloxdownloaded on their mobile devices by using the AppsFlyer version of thelink. The above link would look like:
ro.blox.com/Ebh5?af_dp=https%3A%2F%2Fwww.roblox.com%2Fgames%2Fstart%3FplaceId%3D6900305353%26launchData%3D%257B%2522roomId%2522%253A%25202%257D&af_web_dp=https%3A%2F%2Fwww.roblox.com%2Fgames%2Fstart%3FplaceId%3D6900305353%26launchData%3D%257B%2522roomId%2522%253A%25202%257D
To build the AppsFlyer version of the link, you need to start the URL withro.blox.com/Ebh5? and append the af_dp and af_web_dp parameters with theURL encoded version of Link 1.
Don't store confidential information in the LaunchData because it's fullyvisible in the URL. Furthermore, the data might not be authentic because auser can modify the URL.
Returns
A dictionary containing PlaceId and UserId values (see table indescription).
Code Samples
Tracking Traffic Sources
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local analyticsStore = DataStoreService:GetDataStore("Analytics")
local ALLOWED_SOURCES = {
"twitter";
"youtube";
"discord";
}
local function onPlayerAdded(player)
local source = player:GetJoinData().LaunchData
-- check if the provided source is valid
if source and table.find(ALLOWED_SOURCES, source) then
-- update the data store to track the source popularity
local success, result = pcall(analyticsStore.IncrementAsync, analyticsStore, source)
if success then
print(player.Name, "joined from", source, "- total:", result)
else
warn("Failed to record join source: " .. result)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
Referral URL Generator
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local DIRECT_JOIN_URL = "https://www.roblox.com/games/start?placeId=%d&launchData=%s"
local textBox = script.Parent
local function generateReferralURL(player)
return DIRECT_JOIN_URL:format(
game.PlaceId,
player.UserId
)
end
local function highlightAll()
if -- avoid recursive property updates
textBox:IsFocused()
and not (
textBox.SelectionStart == 1
and textBox.CursorPosition == #textBox.Text + 1
)
then
textBox.SelectionStart = 1
textBox.CursorPosition = #textBox.Text + 1
end
end
textBox.Focused:Connect(highlightAll)
textBox:GetPropertyChangedSignal("SelectionStart"):Connect(highlightAll)
textBox:GetPropertyChangedSignal("CursorPosition"):Connect(highlightAll)
textBox.TextEditable = false
textBox.ClearTextOnFocus = false
textBox.Text = generateReferralURL(player)
Using a Table as Launch Data
local HttpService = game:GetService("HttpService")
local DATA_CHARACTER_LIMIT = 200
local function encodeTableAsLaunchData(data)
-- convert the table to a string
local jsonEncodedData = HttpService:JSONEncode(data)
if #jsonEncodedData <= DATA_CHARACTER_LIMIT then
-- escape potentially invalid characters, such as spaces
local urlEncodedData = HttpService:UrlEncode(jsonEncodedData)
return true, urlEncodedData
else
-- report character limit error
return false, ("Encoded table exceeds %d character limit"):format(DATA_CHARACTER_LIMIT)
end
end
local sampleData = {
joinMessage = "Hello!";
urlCreationDate = os.time();
magicNumbers = {
534;
1337;
746733573;
};
}
local success, encodedData = encodeTableAsLaunchData(sampleData)
if success then
print(encodedData)
else
warn("failed to encode launch data: " .. encodedData)
end
Decoding JSON Launch Data
local HttpService = game:GetService("HttpService")
local Players = game:GetService("Players")
local function onPlayerAdded(player)
local launchData = player:GetJoinData().LaunchData
if launchData then
-- attempt to decode the data
local success, result = pcall(HttpService.JSONDecode, HttpService, launchData)
if success then
print(player.Name, "joined with data:", result)
else
-- this is probably due to the user messing with the URL
warn("Failed to parse launch data:" .. result)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
Server TeleportData Example
local Players = game:GetService("Players")
local approvedPlaceIds = { 1 } -- insert approved PlaceIds here
local function isPlaceIdApproved(placeId)
for _, id in pairs(approvedPlaceIds) do
if id == placeId then
return true
end
end
return false
end
local function onPlayerAdded(player)
local joinData = player:GetJoinData()
-- verify this data was sent by an approved place
if isPlaceIdApproved(joinData.SourcePlaceId) then
local teleportData = joinData.TeleportData
if teleportData then
local currentLevel = teleportData.currentLevel
print(player.Name .. " is on level " .. currentLevel)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
GetMouse
The GetMouse Player function returns the Mouse being usedby the client. The player's mouse instance can be used to track user mouseinput including left and right mouse button clicks and movement andlocation.
The UserInputService service provides additional functions andevents to track user input - especially for devices that do not use amouse.
Note:
This item must be used in a LocalScript to work as expectedonline.
Following an update in July 2014, the mouse's icon can now be set withthis method.
Returns
Code Samples
How to Track Mouse Input
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local function onButton1Down()
print("Button 1 is down")
end
mouse.Button1Down:Connect(onButton1Down)
GetNetworkPing
Write Parallel
GetNetworkPing returns the isolated network latency of thePlayer in seconds. "Ping" is a measurement of the time taken fordata to be sent from the client to the server, then back again. It doesn'tinvolve data deserialization or processing.
For client-side LocalScripts, this function can onlybe called on the Players.LocalPlayer. This function is useful inidentifying and debugging issues that occur in high network latencyscenarios. It's also useful for masking latency, such as adjusting thespeed of throwing animations for projectiles.
Returns
HasAppearanceLoaded
The HasAppearanceLoaded Player function returns whether or not theappearance of the player's Player.Character has loaded.
A player's appearance includes items such as the player's Shirt,Pants, and Accessories.
This is useful when determining whether a player's appearance has loadedafter they first join the game, which can be tracked using thePlayers.PlayerAdded event.
Returns
A boolean indicating whether or not the appearance of the player'scharacter has loaded.
Code Samples
Check if a Player's Appearance Has Loaded
local Players = game:GetService("Players")
local function onPlayerAdded(player)
local loaded = player:HasAppearanceLoaded()
print(loaded)
while not loaded do
loaded = player:HasAppearanceLoaded()
print(loaded)
task.wait()
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
IsVerified
Returns a boolean value indicating that player's verification status. Whentrue, the player is verified. Verification includes, but isn't limited to,non-VOIP phone number or government ID verification.
When implementing IsVerified, exercise caution to ensure that theimplementation does not inadvertently block all unverified users.
Note that the method can only be called on the backend server. Calling itclient-side results in an error. Additionally, this method will alwaysreturn false in Studio.
Returns
A boolean indicating whether the player is verified.
Code Samples
Using IsVerified
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print(player:IsVerified())
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Kick
void
The Kick() method allows an experience to gracefullydisconnect a client and optionally provide a message to the disconnecteduser. This is useful for moderating abusive users. You should only allowspecific users whom you trust to trigger this method on other users.
Calling this method on a Player with no arguments disconnects theuser from the server and provides a default notice message. Calling thismethod on a Player along with a string as the first argumentreplaces the default message with the provided string.
When using this method from a LocalScript, only the local user'sclient can be kicked.
Parameters
message: string
The message to show the user upon kicking.
Default Value: ""
Returns
void
Move
void
The Move Player function causes the player's character to walk inthe given direction until stopped, or interrupted by the player (by usingtheir controls).
This is useful when scripting NPC Humanoids that movearound a map - but are not controlled by an actual player's input.
Note that the function's second argument indicates whether the providedVector3 should move the player relative to world coordinates(false) or the player's Camera (true).
Parameters
walkDirection: Vector3
The Vector3 direction that the player should move.
relativeToCamera: bool
A boolean indicating whether the player should move relative to theplayer's camera.
Default Value: false
Returns
void
Code Samples
Moving the Player relative to their Camera
local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
-- Wait for the player's character and humanoid, which must exist before calling :Move()
local character = localPlayer.Character or localPlayer.CharacterAdded:Wait()
character:WaitForChild("Humanoid")
-- The player will move until they are 50 studs away from the camera's position at the time of running
localPlayer:Move(Vector3.new(0, 0, -50), true)
SetAccountAge
void
Plugin Security
The SetAccountAge function sets the Player.AccountAge of theplayer in days.
It is used to set the Player property that describes how long agoa player's account was registered in days.
This does not set the age of the player on the account, but the age of theaccount itself relative to when it was first created.
Parameters
accountAge: number
The age of the account in days.
Returns
void
Code Samples
Setting the Player's Account Age
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player:SetAccountAge(100)
Account Age Mark
local Players = game:GetService("Players")
local MAX_AGE_NEW_PLAYER = 7 -- one week
local MIN_AGE_VETERAN = 365 -- one year
-- This function marks a part with text using a BillboardGui
local function mark(part, text)
local bbgui = Instance.new("BillboardGui")
bbgui.AlwaysOnTop = true
bbgui.StudsOffsetWorldSpace = Vector3.new(0, 2, 0)
bbgui.Size = UDim2.new(0, 200, 0, 50)
local textLabel = Instance.new("TextLabel")
textLabel.Size = UDim2.new(1, 0, 1, 0) -- Fill parent
textLabel.Text = text
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.BackgroundTransparency = 1
textLabel.Parent = bbgui
-- Add to part
bbgui.Parent = part
bbgui.Adornee = part
end
local function onPlayerSpawned(player, character)
local head = character:WaitForChild("Head")
if player.AccountAge >= MIN_AGE_VETERAN then
mark(head, "Veteran Player")
elseif player.AccountAge <= MAX_AGE_NEW_PLAYER then
mark(head, "New Player")
else
mark(head, "Regular Player")
end
end
local function onPlayerAdded(player)
-- Listen for this player spawning
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
SetSuperSafeChat
void
Plugin Security
This method sets whether or not the player sees chat filtered byTextService:FilterStringAsync() rather than normal chats.
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player:SetSuperSafeChat(true)
Regardless of whether a player has filtered chat enabled, all chat shouldbe filtered by TextService when broadcast to other players or onthe player's own screen. TextService:FilterStringAsync() returns aTextFilterResult object that can be filtered differently accordingto the message's intended use.
Parameters
value: bool
A boolean indicating whether or not the player sees filtered chat.
Returns
void
GetFriendsOnline
Yields
This function returns a dictionary array of online friends, limited by themaxFriends value. The function uses a 30 second cache.
In the returned array, some fields are only present for certain locationtypes. For example, PlaceId won't be present when LocationType is0 (Mobile Website).
Name | Type | Description | ||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
VisitorId | number | The Player.UserId of the friend. | ||||||||||||||
UserName | string | The username of the friend. | ||||||||||||||
DisplayName | string | The Player.DisplayName of the friend. | ||||||||||||||
LastOnline | string | When the friend was last online. | ||||||||||||||
IsOnline | boolean | If the friend is currently online. | ||||||||||||||
LastLocation | string | The name of the friend's current location. | ||||||||||||||
PlaceId | number | The place ID of the friend's last location. | ||||||||||||||
GameId | string | The DataModel/JobId of the friend's last location. | ||||||||||||||
LocationType | number | The location type of the friend's last location:
|
Parameters
maxFriends: number
The maximum number of online friends to return.
Default Value: 200
Returns
A dictionary of online friends (see the table above).
Code Samples
Get a List of Online Friends
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local success, result = pcall(player.GetFriendsOnline, player, 10)
if success then
for _, friend in pairs(result) do
print(friend.UserName)
end
else
warn("Failed to get online players: " .. result)
end
GetRankInGroup
Yields
The GetRankInGroup Player function returns the player's rank inthe group as an integer between 0 and 255, where 0 is a non-member and 255is the group's owner.
Using this in a Script, as opposed to a LocalScript, willnot get you the most up-to-date information. If a player leaves a groupwhile they are in the game, GetRankInGroup will still think they're inthat group until they leave. However, this does not happen when used witha LocalScript.
This is because the method caches results, so multiple calls ofGetRankInGroup on the same player with the same group ID will yield thesame result as when the method was first called with the given group ID.The caching behavior is on a per-peer basis: a server does not share thesame cache as a client.
Parameters
groupId: number
The groupId of the specified group.
Returns
The player's rank in the group.
Code Samples
How to Check a Player's Rank in a Group
local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:GetRankInGroup(2) == 255 then
print("Player is the owner of the group, 'LOL'!")
else
print("Player is NOT the owner of the group, 'LOL'!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
GetRoleInGroup
Yields
The GetRoleInGroup Player function returns the player's role inthe group as a string, or Guest if the player isn't part of the group.
Using this in a Script, as opposed to a LocalScript, willnot get you the most up-to-date information. If a player leaves a groupwhile they are in the game, GetRoleInGroup will still think they're inthat group until they leave. However, this does not happen when used witha LocalScript.
This is because the method caches results, so multiple calls ofGetRoleInGroup on the same player with the same group ID will yield thesame result as when the method was first called with the given group ID.The caching behavior is on a per-peer basis: a server does not share thesame cache as a client.
Parameters
groupId: number
The groupId of the specified group.
Returns
The player's role in the specified group, or Guest of the player isnot a member.
Code Samples
How to Check a Player's Role in a Group
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print("Player is ranked as '", player:GetRoleInGroup(2), "' in group, 'LOL'!")
end
Players.PlayerAdded:Connect(onPlayerAdded)
IsFriendsWith
Yields
This function sends a request to the Roblox website asking whether aplayer is a friend of another user, given the Player.UserId ofthat user. This function caches results so multiple calls of the functionon the same player with the same Player.UserId may not yield themost up-to-date result. This does not happen when used in aLocalScript.
Parameters
userId: number
The Player.UserId of the specified player.
Returns
A boolean indicating whether a player is a friend of the specifieduser.
Code Samples
How to Check if a Player is a Friend
local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:IsFriendsWith(146569) then
print(player.Name .. " is friends with gordonrox24!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
IsInGroup
Yields
The IsInGroup Player function sends a request to the Robloxwebsite asking whether a player is a member of a group, given the ID ofthat group.
Using this in a Script, as opposed to a LocalScript, willnot get you the most up-to-date information. If a player leaves a groupwhile they are in the game, IsInGroup will still think they're in thatgroup until they leave. However, this does not happen when used with aLocalScript.
This is because the method caches results, so multiple calls of IsInGroupon the same player with the same group ID will yield the same result aswhen the method was first called with the given group ID. The cachingbehavior is on a per-peer basis: a server does not share the same cache asa client.
Parameters
groupId: number
The groupId of the specified group.
Returns
A boolean indicating whether the player is in the specified group.
Code Samples
How to Check if a Player is in a Group
local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:IsInGroup(7) then
print("Player is in the Roblox Fan club!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
LoadCharacter
void
Yields
The LoadCharacter Player function creates a new character for theplayer, removing the old one. It also clears the player's Backpackand PlayerGui.
This is useful in cases where you want to reload the character withoutkilling the player, such as when you want to load a new characterappearance after changing the player's Player.CharacterAppearance.
Note: The function is similar to Player:LoadCharacterBlocking(),but the request is processed asynchronously instead of synchronously. Thismeans other tasks will be able to continue while the character is beingloaded, including the rendering of the game and any other tasks. Also,this function can be used in a script, while LoadCharacterBlocking cannot.
After calling LoadCharacter for an individual player, it is notrecommended to call it again for the same player until after that player'sPlayer.CharacterAppearanceLoaded event has fired.
Character Loading Event order
Calling the Player:LoadCharacter() with an R15 Avatar fires eventsin the following order (Note: R6 ordering is different):
Player.Character sets
Player.CharacterAdded fires
Player.Changed fires with a value of "Character"
Character appearance initializes
Player.CharacterAppearanceLoaded fires
Character.Parent sets to the DataModel
The Character rig builds, and the Character scales
Character moves to the spawn location
LoadCharacter returns
Returns
void
Code Samples
Turn Off Auto-Loading and Simulate Character Respawn
local Players = game:GetService("Players")
local RESPAWN_DELAY = 5
Players.CharacterAutoLoads = false
local function onPlayerAdded(player)
local function onCharacterAdded(character)
local humanoid = character:WaitForChild("Humanoid")
local function onDied()
task.wait(RESPAWN_DELAY)
player:LoadCharacter()
end
humanoid.Died:Connect(onDied)
end
player.CharacterAdded:Connect(onCharacterAdded)
player:LoadCharacter()
end
Players.PlayerAdded:Connect(onPlayerAdded)
LoadCharacterWithHumanoidDescription
void
Yields
This function spawns an avatar so it has everything equipped in the passedin HumanoidDescription.
After calling LoadCharacterWithHumanoidDescription for an individualplayer, it is not recommended to call the function again for the sameplayer until after that player's Player.CharacterAppearanceLoadedevent has fired.
See also:
HumanoidDescription System,an article which explains the humanoid description system in greaterdetail and provides several scripting examples
Parameters
humanoidDescription: HumanoidDescription
A HumanoidDescription containing traits like bodyparts/colors, body scaling, accessories, clothing, and animations thatwill be equipped to the loaded character.
Returns
void
Code Samples
Spawn Characters With HumanoidDescription
local Players = game:GetService("Players")
Players.CharacterAutoLoads = false
local function onPlayerAdded(player)
local humanoidDescription = Instance.new("HumanoidDescription")
humanoidDescription.HatAccessory = "2551510151,2535600138"
humanoidDescription.BodyTypeScale = 0.1
humanoidDescription.ClimbAnimation = 619521311
humanoidDescription.Face = 86487700
humanoidDescription.GraphicTShirt = 1711661
humanoidDescription.HeadColor = Color3.new(0, 1, 0)
player:LoadCharacterWithHumanoidDescription(humanoidDescription)
end
Players.PlayerAdded:Connect(onPlayerAdded)
RequestStreamAroundAsync
void
Yields
For experiences where instancestreaming is enabled, requests that theserver stream to the player regions (parts and terrain) around thespecified X, Y, Z location in the 3D world. It is useful ifthe experience knows that the player's CFrame will be set tothe specified location in the near future. Without providing the locationwith this call, the player may not have streamed in content for thedestination, resulting in a streaming pause or other undesirable behavior.
The effect of this call will be temporary and there are no guarantees ofwhat will be streamed in around the specified location. Client memorylimits and network conditions may impact what will be available on theclient.
Usage Precaution
Requesting streaming around an area is not a guarantee that thecontent will be present when the request completes, as streaming isaffected by the client's network bandwidth, memory limitations, and otherfactors.
Parameters
position: Vector3
World location where streaming is requested.
timeOut: number
Optional timeout for the request.
Default Value: 0
Returns
void
Events
CharacterAdded
The CharacterAdded event fires when a player's character spawns (orrespawns). This event fires soon after setting Player.Character toa non-nil value or calling Player:LoadCharacter(), which isbefore the character is parented to the Workspace.
This can be used alongside the Player.CharacterRemoving event,which fires right before a player's character is about to be removed,typically after death. As such, both of these events can potentially firemany times as players die then respawn in a place. If you want to detectwhen a player joins or leaves the game, use thePlayers.PlayerAdded and Players.PlayerRemoving eventsinstead.
Note that the Humanoid and its default body parts (head, torso,and limbs) will exist when this event fires, but clothing items likeHats, Shirts, and Pants may take a fewseconds to be added to the character. Connect Instance.ChildAddedon the added character to detect these, or wait for thePlayer.CharacterAppearanceLoaded event to be sure the characterhas everything equipped.
Parameters
character: Model
An instance of the character that spawned/respawned.
Code Samples
Detecting Player Spawns and Despawns
local Players = game:GetService("Players")
local function onCharacterAdded(character)
print(character.Name .. " has spawned")
end
local function onCharacterRemoving(character)
print(character.Name .. " is despawning")
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
player.CharacterRemoving:Connect(onCharacterRemoving)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Respawn at Despawn Location
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
-- This table maps "Player" objects to Vector3
local respawnLocations = {}
local function onCharacterAdded(character)
local player = Players:GetPlayerFromCharacter(character)
-- Check if we saved a respawn location for this player
if respawnLocations[player] then
-- Teleport the player there when their HumanoidRootPart is available
local hrp = character:WaitForChild("HumanoidRootPart")
-- Wait a brief moment before teleporting, as Roblox will teleport the
-- player to their designated SpawnLocation (which we will override)
RunService.Stepped:wait()
hrp.CFrame = CFrame.new(respawnLocations[player] + Vector3.new(0, 3.5, 0))
end
end
local function onCharacterRemoving(character)
-- Get the player and their HumanoidRootPart and save their death location
local player = Players:GetPlayerFromCharacter(character)
local hrp = character:FindFirstChild("HumanoidRootPart")
if hrp then
respawnLocations[player] = hrp.Position
end
end
local function onPlayerAdded(player)
-- Listen for spawns/despawns
player.CharacterAdded:Connect(onCharacterAdded)
player.CharacterRemoving:Connect(onCharacterRemoving)
end
local function onPlayerRemoved(player)
-- Forget the respawn location of any player who is leaving; this prevents
-- a memory leak if potentially many players visit
respawnLocations[player] = nil
end
-- Note that we're NOT using PlayerRemoving here, since CharacterRemoving fires
-- AFTER PlayerRemoving, we don't want to forget the respawn location then instantly
-- save another right after
Players.PlayerAdded:Connect(onPlayerAdded)
Players.ChildRemoved:Connect(onPlayerRemoved)
Accessory Remover
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local function destroyAccessory(object)
if object:IsA("Hat") or object:IsA("Accessory") then
object:Destroy()
end
end
local function onCharacterAdded(character)
-- Wait a brief moment before removing accessories to avoid the
-- "Something unexpectedly set ___ parent to NULL" warning
RunService.Stepped:Wait()
-- Check for any existing accessories in the player's character
for _, child in pairs(character:GetChildren()) do
destroyAccessory(child)
end
-- Hats may be added to the character a moment after
-- CharacterAdded fires, so we listen for those using ChildAdded
character.ChildAdded:Connect(destroyAccessory)
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)
CharacterAppearanceLoaded
This event fires when the full appearance of a Player.Characterhas been inserted.
A Player.Character generally has a range of objects modifying itsappearance, including Accoutrements,Shirts, Pants andCharacterMeshes. This event will fire when all suchobjects have been inserted into the Player.Character.
One use for this event is to ensure all accessories have loaded beforedestroying them. See below for an example of this.
Parameters
character: Model
The Player.Character Model.
Code Samples
Remove Accessories After Loading
local Players = game:GetService("Players")
local function onPlayerAddedAsync(player)
local connection = player.CharacterAppearanceLoaded:Connect(function(character)
-- All accessories have loaded at this point
local numAccessories = #character:GetAccessories()
print(("Destroying %d accessories for %s"):format(numAccessories, player.Name))
local humanoid = character:FindFirstChildOfClass("Humanoid")
humanoid:RemoveAccessories()
end)
-- Make sure we disconnect our connection to the player after they leave
-- to allow the player to get garbage collected
player.AncestryChanged:Wait()
connection:Disconnect()
end
for _, player in Players:GetPlayers() do
task.spawn(onPlayerAddedAsync, player)
end
Players.PlayerAdded:Connect(onPlayerAddedAsync)
CharacterRemoving
The CharacterRemoving event fires right before a player's character isremoved, such as when the player is respawning.
This event can be used alongside the Player.CharacterAdded event,which fires when a player's character spawns or respawns. For instance, ifyou would like to print a message every time a player spawns and dies:
local Players = game:GetService("Players")
local function onCharacterSpawned(player)
print(player.Name .. " is spawning")
end
local function onCharacterDespawned(player)
print(player.Name .. " is despawning")
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(function ()
onCharacterSpawned(player)
end)
player.CharacterRemoving:Connect(function ()
onCharacterDespawned(player)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
This event is only concerned with the Characterof a Player. If you instead need to track when a playerjoins/leaves the game, use the events Players.PlayerAdded andPlayers.PlayerRemoving.
Parameters
character: Model
An instance of the character that is being removed.
Code Samples
Player.CharacterRemoving
game.Players.PlayerAdded:Connect(function(player)
player.CharacterRemoving:Connect(function(character)
print(character.Name .. " has died.")
end)
end)
Chatted
The Chatted event fires when a Player types a message and pressesenter in Roblox's provided chat bar. This is done using some Lua bindingsby the default chat script. You can prevent players from chatting by usingStarterGui:SetCoreGuiEnabled() and disabling the ChatEnum.CoreGuiType.
Chat Commands
Using this event and some string manipulation functions likestring.sub() and string.lower(), it is possible tocreate chat commands, even with arguments like player names. Usually,commands are prefixed such as heal PlayerName. To check for a prefix ina string, use string.sub() on the message to check a substringof the message: string.sub(message, 1, 6) == "/heal " (note theinclusion of the space). Then, extract the rest of the command usingstring.sub() again: string.sub(message, 7) will be equal tothe player name. Check if that player exists, and if so, perform thecommand's action (in this example, healing them). Check the code samplesfor examples of chat commands.
Filtering
The message text fired with this event is unfiltered. If you aredisplaying player input like chat to other players in any form, it must befiltered using Chat:FilterStringAsync(). Keep this in mind whencreating your own chat systems; if your game does not properly filter chatit may have moderation action taken against it.
Parameters
message: string
The content of the message the player typed in chat.
recipient: Player
Deprecated. For whisper messages, this was the Player who was theintended target of the chat message.
Code Samples
Player.Chatted
local Players = game:GetService("Players")
local function onPlayerAdded(player)
local function onChatted(message)
-- do stuff with message and player
print(message)
end
player.Chatted:Connect(onChatted)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Playing/Spectating Teams
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
local teamPlaying = Teams.Playing
local teamSpectators = Teams.Spectating
local playCommand = "/play"
local function play(player)
player.Team = teamPlaying
player.TeamColor = teamPlaying.TeamColor
-- Respawn the player (moves them to spawn location)
player:LoadCharacter()
end
local function onPlayerDied(player, _character)
-- When someone dies, put them on the spectator team
player.Team = teamSpectators
end
local function onPlayerSpawned(player, character)
local human = character:WaitForChild("Humanoid")
human.Died:Connect(function()
onPlayerDied(player, character)
end)
end
local function onPlayerChatted(player, message)
if message:sub(1, playCommand:len()):lower() == playCommand then
play(player)
end
end
local function onPlayerAdded(player)
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
player.Chatted:Connect(function(message, _recipient)
onPlayerChatted(player, message)
end)
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Join Team Command
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
-- Command to choose a team (note the trailing space)
local joinCommand = "/jointeam "
local function findTeamByName(name)
-- First, check for the exact name of a team
if Teams:FindFirstChild(name) then
return Teams[name]
end
-- Let's check for case-insensitive partial matches, like "red" for "Red Robins"
for _, team in pairs(Teams:GetChildren()) do
if team.Name:sub(1, name:len()):lower() == name:lower() then
return team
end
end
-- If we get to this point, no team matched the one we were looking for :(
end
local function onPlayerChatted(player, message, _recipient)
-- Note: string.sub(message, ...) is the same as message:sub(...)
if message:sub(1, joinCommand:len()):lower() == joinCommand:lower() then
-- Matched "/JOINTEAM xyz" to our join command prefix "/jointeam "
local teamName = message:sub(joinCommand:len() + 1) -- Cut out the "xyz" from "/jointeam xyz"
local team = findTeamByName(teamName)
if team then
-- Set the team!
player.Team = team
player.Neutral = false
else
-- Tell the player that team could not be found :(
player.Team = nil
player.Neutral = true
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Idled
This event fires approximately two minutes after the game engineclassifies the player as idle. Time is the number ofseconds that have elapsed since that point. The event continues to fireevery 30 seconds for as long as the player remains idle.
This event only fires in client scripts, not server scripts; use aRemoteEvent to notify the server of idle players.
Roblox automatically disconnects players that have been idle for at least20 minutes, so this event is useful for warning players that they will bedisconnected soon, disconnecting players prior to those 20 minutes, orother away from keyboard (AFK) features.
To track how often automatic disconnects occur, try correlating this eventwith occurrences of Players.PlayerRemoving.
Parameters
time: number
The time in seconds the player has been idle.
Code Samples
Player.Idled
local Players = game:GetService("Players")
local function onIdled(idleTime)
print(`Player has been idle for {idleTime} seconds`)
if idleTime > 900 then
-- warn player that they've been idle for 15 minutes
-- and will be disconnected in another 5
end
end
Players.LocalPlayer.Idled:Connect(onIdled)
OnTeleport
Fired when the TeleportState of a player changes. This event is useful fordetecting whether a teleportation was successful.
What is the TeleportState?
When a teleportation request is made using TeleportService, thereare a series of stages before the Player is teleported. Thecurrent stage is represented by the Enum.TeleportState value which isgiven by OnTeleport. See below for a practical example of this.
Parameters
teleportState: Enum.TeleportState
The new Enum.TeleportState of the Player.
spawnName: string
The name of the spawn to teleport to, ifTeleportService:TeleportToSpawnByName() has been used.
Code Samples
Player.OnTeleport
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local playerOnTeleport = player
player.OnTeleport:Connect(function(teleportState, _placeId, _spawnName)
if teleportState == Enum.TeleportState.Started then
print("Teleport started (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.WaitingForServer then
print("Teleport waiting for server (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.InProgress then
print("Teleport in progress (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.Failed then
print("Teleport failed! (" .. playerOnTeleport.Name .. ")")
end
end)
end)