Player
A Player object is a client that is currently connected. These objects are added to the Players service when a new player connects, then removed when they eventually disconnect from the server.
The Instance.Name property reflects the player's username. When saving information about a player, you should use their UserId since it is possible that a player can change their username.
There are several similar methods in the Players service for working with Player objects. Use these over their respective Instance methods:
- You can get a table of current Player objects using Players:GetPlayers(); again, use this instead of Instance:GetChildren().
- To detect the addition of Player objects, it is recommended to use the Players.PlayerAdded event (instead of Instance.ChildAdded on the Players service).
- Similarly, you can detect the removal of Player objects using Players.PlayerRemoving, which fires just before the Player is removed (instead of Instance.ChildRemoved which fires after). This is important if you are saving information about the player that might be removed or cleaned up on removal.
Summary
Properties
Describes the player's account age in days.
Determines whether the character of a player using a mobile device will automatically jump upon hitting an obstacle.
The maximum distance the player's camera is allowed to zoom out.
The minimum distance the player's camera is allowed to zoom in.
Changes the camera's mode to either first or third person.
Determines whether the character's appearance will be loaded when the player spawns. If false, the player will spawn with a default appearance.
A Model controlled by the player that contains a Humanoid, body parts, scripts, and other objects.
Determines the user ID of the account whose character appearance is used for a player's Character.
Sets how the default camera handles objects between the camera and the player.
Determines player's camera movement mode when using a device with a mouse and keyboard.
Determines player's character movement mode when using a device with a mouse and keyboard.
Determines if the player can toggle mouse lock.
Determines player's camera movement mode when using a touch-enabled device.
Determines player's character movement mode when using a touch-enabled device.
The display name of the authenticated user associated with the Player.
Describes the user ID of the player who was followed into an experience by a player.
Whether player client-side gameplay is currently paused.
Indicates if a player has a Verified badge.
Sets the distance at which this player will see other players' health bars.
This property shows the locale ID that the local player has set for their Roblox account.
Describes the account's membership type.
Sets the distance at which this player will see other players' names.
Determines whether the player is on a specific team.
A unique identifier of the party a Player belongs to.
Sets the part to focus replication around.
If set, the player will respawn at the given SpawnLocation.
Determines the Team with which the player is associated.
Determines the Team with which the player is associated with according to that team's Team.TeamColor.
A unique identifying integer assigned to all user accounts.
Methods
Removes all accessories and other character appearance objects from a player's Character.
Returns the distance between the character's head and the given Vector3, or 0 if the player has no character.
Returns a dictionary of online connections.
Returns a dictionary containing information describing how the player joins the experience.
Returns the mouse being used by the client.
Returns the isolated network latency in seconds.
Returns the player's rank in the group as an integer.
Returns the player's role in the group as a string, or Guest if the player isn't part of the group.
Returns whether or not the appearance of the player's character has loaded.
Checks whether a player is a connection of the user with the given Player.UserId.
Checks whether a player is a member of a group with the given ID.
Returns whether the player is verified with concrete, real-world signals.
Forcibly disconnect a player from the experience, optionally providing a message.
Creates a new character for the player, removing the old one. Also clears the player's Backpack and PlayerGui.
Spawns a player character with everything equipped in the passed in HumanoidDescription.
Causes the player's character to walk in the given direction until stopped, or interrupted by the player (by using their controls).
Requests that the server stream to the player around the specified location.
Sets the AccountAge of the player.
Sets whether or not the player sees filtered chats, rather than normal chats.
Events
Fires when a player's character spawns or respawns.
Fires when the full appearance of a Character has been inserted.
Fires right before a player's character is removed.
Fires when a player chats in experience using Roblox's provided chat bar.
This event fires approximately two minutes after the engine classifies the player as idle. Time is the number of seconds that have elapsed since that point.
Fires when the teleport state of a player changes.
Properties
AccountAge
AutoJumpEnabled
Code Samples
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
CameraMinZoomDistance
CameraMode
Code Samples
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMode = Enum.CameraMode.LockFirstPerson
CanLoadCharacterAppearance
Character
CharacterAppearanceId
DevCameraOcclusionMode
DevComputerCameraMode
DevComputerMovementMode
DevEnableMouseLock
DevTouchCameraMode
DevTouchMovementMode
DisplayName
FollowUserId
Code Samples
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local screenGui = Instance.new("ScreenGui")
screenGui.Parent = player:WaitForChild("PlayerGui")
local function onPlayerAdded(newPlayer)
if newPlayer.FollowUserId == player.UserId then
local textLabel = Instance.new("TextLabel")
textLabel.Parent = screenGui
textLabel.Text = "You were followed to this game by " .. newPlayer.Name .. "!"
task.delay(3, function()
if textLabel then
textLabel:Destroy()
end
end)
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
GameplayPaused
HasVerifiedBadge
HealthDisplayDistance
LocaleId
MembershipType
Code Samples
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
Neutral
PartyId
Code Samples
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local partyId = player.PartyId
if partyId ~= "" then
print("Player is in a party with ID: " .. partyId)
else
warn("Player is not in a party")
end
end)
ReplicationFocus
RespawnLocation
Code Samples
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
StepIdOffset
Team
TeamColor
ThirdPartyTextChatRestrictionStatus
UserId
Code Samples
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print(player.UserId)
end
Players.PlayerAdded:Connect(onPlayerAdded)
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
Returns
Code Samples
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
Parameters
Returns
Code Samples
local Players = game:GetService("Players")
for _, player in pairs(Players:GetPlayers()) do
print(player:DistanceFromCharacter(Vector3.new(0, 0, 0)))
end
GetData
Returns
GetFriendsOnline
Parameters
Returns
Code Samples
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
GetJoinData
Returns
Code Samples
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)
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)
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
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)
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)
GetRankInGroup
Parameters
Returns
Code Samples
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
Parameters
Returns
Code Samples
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)
HasAppearanceLoaded
Returns
Code Samples
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)
IsFriendsWith
Parameters
Returns
Code Samples
local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:IsFriendsWith(146569) then
print(player.Name .. " is connections with gordonrox24!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
IsVerified
Returns
Code Samples
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)
LoadCharacter
Returns
Code Samples
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)
LoadCharacterAppearance
Parameters
Returns
Code Samples
local Players = game:GetService("Players")
local InsertService = game:GetService("InsertService")
local function onPlayerAdded(player)
local function onChatted(message)
local assetId = message:match("id=(%d+)")
if assetId then
local model = InsertService:LoadAsset(assetId)
for _, child in pairs(model:GetChildren()) do
player:LoadCharacterAppearance(child)
end
end
end
player.Chatted:Connect(onChatted)
end
Players.PlayerAdded:Connect(onPlayerAdded)
LoadCharacterWithHumanoidDescription
Parameters
Returns
Code Samples
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)
LoadInstance
Parameters
Returns
Code Samples
local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:WaitForDataReady() then
local model = player:LoadInstance("Model")
model.Parent = workspace
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
LoadNumber
Parameters
Returns
Code Samples
local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:WaitForDataReady() then
print(player:LoadNumber("TotalPlays"))
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
LoadString
Parameters
Returns
Code Samples
game.Players.PlayerAdded:Connect(function(Player)
if Player:WaitForDataReady() then
print(Player:LoadString("TheirName"))
end
end)
Move
Parameters
Returns
Code Samples
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)
SaveBoolean
Parameters
Returns
Code Samples
game.Players.PlayerAdded:Connect(function(Player)
if Player:WaitForDataReady() then
Player:SaveBoolean("HasPlayed", true)
end
end)
SaveInstance
Parameters
Returns
Code Samples
game.Players.PlayerAdded:Connect(function(Player)
Player:WaitForDataReady()
Player:SaveInstance("Model", game.Workspace.Model)
end)
SaveNumber
Parameters
Returns
Code Samples
game.Players.PlayerAdded:Connect(function(Player)
if Player:WaitForDataReady() then
local OldValue = Player:SaveNumber("TotalPlays")
Player:SaveNumber("TotalPlays", OldValue + 1)
end
end)
SaveString
Parameters
Returns
Code Samples
local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:WaitForDataReady() then
player:SaveString("TheirName", player.Name)
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
Events
CharacterAdded
Parameters
Code Samples
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)
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
Parameters
Code Samples
local Players = game:GetService("Players")
local function onPlayerAddedAsync(player)
local connection = player.CharacterAppearanceLoaded:Connect(function(character)
-- All accessories have loaded at this point
local humanoid = character:FindFirstChildOfClass("Humanoid")
local numAccessories = #humanoid:GetAccessories()
print(("Destroying %d accessories for %s"):format(numAccessories, player.Name))
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
Parameters
Code Samples
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)
OnTeleport
Parameters
Code Samples
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)