Players
Summary
Properties
Methods
Events
PlayerAdded(player: Player):RBXScriptSignal |
PlayerMembershipChanged(player: Player):RBXScriptSignal |
PlayerRemoving(player: Player,reason: Enum.PlayerExitReason):RBXScriptSignal |
UserSubscriptionStatusChanged(user: Player,subscriptionId: string):RBXScriptSignal |
API Reference
Properties
Character Auto Loads
Code Samples
Player Respawn Timer
local Players = game:GetService("Players")
-- Set CharacterAutoLoads to false
Players.CharacterAutoLoads = false
-- Remove player's character from workspace on death
Players.PlayerAdded:Connect(function(player)
while true do
local char = player.CharacterAdded:Wait()
char.Humanoid.Died:Connect(function()
char:Destroy()
end)
end
end)
-- Respawn all dead players once every 10 seconds
while true do
local players = Players:GetChildren()
-- Check if each player is dead by checking if they have no character, if dead load that player's character
for _, player in pairs(players) do
if not workspace:FindFirstChild(player.Name) then
player:LoadCharacterAsync()
end
end
-- Wait 10 seconds until next respawn check
task.wait(10)
endlocal Player
Num Players
num Players
Methods
Ban Async
Parameters
Returns
()
Code Samples
Banning Users
local Players = game:GetService("Players")
local function shouldBeBanned(player: Player): boolean
-- Replace with your own moderation logic
return false
end
Players.PlayerAdded:Connect(function(player)
if shouldBeBanned(player) then
local banHistoryPages = Players:GetBanHistoryAsync(player.UserId)
print(banHistoryPages:GetCurrentPage())
local duration = 86400 -- 24 hours in seconds. Recommendation: use your own logic based off of user's BanHistory
local config: BanConfigType = {
UserIds = { player.UserId },
Duration = duration,
DisplayReason = "You violated community guideline #5",
PrivateReason = "Put anything here that the user should not know but is helpful for your records",
ExcludeAltAccounts = false,
ApplyToUniverse = true,
}
local success, err = pcall(function()
return Players:BanAsync(config)
end)
print(success, err)
end
end)Chat
Parameters
Returns
()
Code Samples
Players:Chat
-- Command bar
game:GetService("Players"):Chat("Hello, world!") --Results in 'Hello, world!' appearing in the Chat log under your Player's name.
-- Script
local Players = game:GetService("Players")
Players:Chat("Hello, world!") --ErrorsCreate Humanoid Model From Description
Create Humanoid Model From Description Async
Players: Create Humanoid Model From Description Async(
description:HumanoidDescription, rig Type:Enum.HumanoidRigType, asset Type Verification:Enum.AssetTypeVerification
Parameters
| Default Value: Default |
Returns
Code Samples
Create Humanoid Model From Description
local Players = game:GetService("Players")
Players:CreateHumanoidModelFromDescriptionAsync(Instance.new("HumanoidDescription"), Enum.HumanoidRigType.R15).Parent =
game.WorkspaceCreate Humanoid Model From User Id
Create Humanoid Model From User Id Async
Get Ban History Async
Get Character Appearance Async
Get Character Appearance Info Async
Parameters
Returns
Code Samples
Get Character Appearance Info
local Players = game:GetService("Players")
-- The user ID to look up (1 is the Roblox account)
local USER_ID = 1
-- The call reaches the Roblox website, so it can fail
local success, appearanceInfo = pcall(function()
return Players:GetCharacterAppearanceInfoAsync(USER_ID)
end)
if not success then
warn("Could not get appearance info:", appearanceInfo)
return
end
print("Avatar type:", appearanceInfo.playerAvatarType) --> R15 or R6
print("Height scale:", appearanceInfo.scales.height)
-- List every asset the avatar is wearing
for _, asset in appearanceInfo.assets do
print(`{asset.assetType.name}: {asset.name} ({asset.id})`)
endGet Friends Async
Parameters
Returns
Code Samples
Print Roblox Friends
local Players = game:GetService("Players")
local USERNAME = "Cozecant"
-- First, get the user ID of the player
local userId = Players:GetUserIdFromNameAsync(USERNAME)
-- Then, get a FriendPages object for their friends
local friendPages = Players:GetFriendsAsync(userId)
-- Walk the pages, collecting the username of every friend. Each page entry is
-- a table of information about the friend, including Username.
local usernames = {}
while true do
for _, friend in ipairs(friendPages:GetCurrentPage()) do
table.insert(usernames, friend.Username)
end
if friendPages.IsFinished then
break
end
friendPages:AdvanceToNextPageAsync()
end
print("Friends of " .. USERNAME .. ": " .. table.concat(usernames, ", "))Get Humanoid Description From Outfit Id
Get Humanoid Description From Outfit Id Async
Parameters
Returns
Code Samples
Get HumanoidDescription From Outfit ID
local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local AssetService = game:GetService("AssetService")
local function getOutfitId(bundleId)
if bundleId <= 0 then
return
end
local info = AssetService:GetBundleDetailsAsync(bundleId)
if not info then
return
end
for _, item in pairs(info.Items) do
if item.Type == "UserOutfit" then
return item.Id
end
end
return nil
end
local function getHumanoidDescriptionBundle(bundleId)
local itemId = getOutfitId(bundleId)
if itemId and itemId > 0 then
return Players:GetHumanoidDescriptionFromOutfitIdAsync(itemId)
end
return nil
end
local humanoidDescription = getHumanoidDescriptionBundle(799)
local humanoidModel = Players:CreateHumanoidModelFromDescriptionAsync(humanoidDescription, Enum.HumanoidRigType.R15)
humanoidModel.Parent = WorkspaceGet Humanoid Description From User Id
Get Humanoid Description From User Id Async
Parameters
Returns
Code Samples
Get HumanoidDescription From User ID
local Players = game:GetService("Players")
Players:CreateHumanoidModelFromDescriptionAsync(
Players:GetHumanoidDescriptionFromUserIdAsync(1),
Enum.HumanoidRigType.R15
).Parent =
game.WorkspaceGet Name From User Id Async
Parameters
Returns
Code Samples
Get Name from UserId
local Players = game:GetService("Players")
-- Example Data:
-- UserId: 118271 Name: "RobloxRulez"
-- UserId: 131963979 Name: "docsRule"
local nameOne = Players:GetNameFromUserIdAsync(118271)
local nameTwo = Players:GetNameFromUserIdAsync(131963979)
print(nameOne, nameTwo)
-- prints: "RobloxRulez docsRule"Get Name from UserId using a cache
local Players = game:GetService("Players")
-- Create a table called 'cache' to store each 'Name' as they are found.
-- If we lookup a 'Name' using the same 'UserId', the 'Name' will come
-- from cache (fast) instead of GetNameFromUserIdAsync() (yields).
local cache = {}
function getNameFromUserId(userId)
-- First, check if the cache contains 'userId'
local nameFromCache = cache[userId]
if nameFromCache then
-- if a value was stored in the cache at key 'userId', then this 'nameFromCache'
-- is the correct Name and we can return it.
return nameFromCache
end
-- If here, 'userId' was not previously looked up and does not exist in the
-- cache. Now we need to use GetNameFromUserIdAsync() to look up the name
local name
local success, _ = pcall(function()
name = Players:GetNameFromUserIdAsync(userId)
end)
if success then
-- if 'success' is true, GetNameFromUserIdAsync() successfully found the
-- name. Store this name in the cache using 'userId' as the key so we
-- never have to look this name up in the future. Then return name.
cache[userId] = name
return name
end
-- If here, 'success' was false, meaning GetNameFromUserIdAsync()
-- was unable to find the 'name' for the 'userId' provided. Warn the user
-- this happened and then return nothing, or nil.
warn("Unable to find Name for UserId:", userId)
return nil
end
-- Example Data:
-- UserId: 118271 Name: "RobloxRulez"
-- UserId: 131963979 Name: "docsRule"
-- The first time a UserId is used, GetNameFromUserIdAsync() will be called
local nameOne = getNameFromUserId(118271)
local nameTwo = getNameFromUserId(131963979)
-- Because 118271 was previously used, get its Name from the cache
local nameOneQuick = getNameFromUserId(118271)
print(nameOne, nameTwo, nameOneQuick)
-- prints: "RobloxRulez docsRule RobloxRulez"Get Player By User Id
Parameters
Returns
Code Samples
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!")
endGet Player From Character
Parameters
Returns
Code Samples
Players:GetPlayerFromCharacter
local Players = game:GetService("Players")
local Workspace = game:GetService("Workspace")
local PLAYER_NAME = "Nightriff"
local character = Workspace:FindFirstChild(PLAYER_NAME)
local player = Players:GetPlayerFromCharacter(character)
if player then
print(`Player {player.Name} ({player.UserId}) is in the game`)
else
print(`Player {PLAYER_NAME} is not in the game!`)
endGet Players
Returns
{Player}
Code Samples
Give Sparkles to Everyone
local Players = game:GetService("Players")
local function onCharacterAdded(character)
-- Give them sparkles on their head if they don't have them yet
if not character:FindFirstChild("Sparkles") then
local sparkles = Instance.new("Sparkles")
sparkles.Parent = character:WaitForChild("Head")
end
end
local function onPlayerAdded(player)
-- Check if they already spawned in
if player.Character then
onCharacterAdded(player.Character)
end
-- Listen for the player (re)spawning
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)get Players
Get Profile Configuration From User Id Async
Get User Id From Name Async
Parameters
Returns
Code Samples
Get UserId from Name
local Players = game:GetService("Players")
-- Example Data:
-- UserId: 118271 Name: "RobloxRulez"
-- UserId: 131963979 Name: "docsRule"
local userIdOne = Players:GetUserIdFromNameAsync("RobloxRulez")
local userIdTwo = Players:GetUserIdFromNameAsync("docsRule")
print(userIdOne, userIdTwo)
-- prints: "118271 131963979"Get UserId from Name using a cache
local Players = game:GetService("Players")
-- Create a table called 'cache' to store each 'UserId' as they are found.
-- If we lookup a 'UserId' using the same 'Name', the 'UserId' will come
-- from cache (fast) instead of GetUserIdFromNameAsync() (yields).
local cache = {}
function getUserIdFromName(name)
-- First, check if the cache contains 'name'
local userIdFromCache = cache[name]
if userIdFromCache then
-- if a value was stored in the cache at key 'name', then this 'userIdFromCache'
-- is the correct UserId and we can return it.
return userIdFromCache
end
-- If here, 'name' was not previously looked up and does not exist in the
-- cache. Now we need to use GetUserIdFromNameAsync() to look up the userId
local userId
local success, _ = pcall(function()
userId = Players:GetUserIdFromNameAsync(name)
end)
if success then
-- if 'success' is true, GetUserIdFromNameAsync() successfully found the
-- userId. Store this userId in the cache using 'name' as the key so we
-- never have to look this userId up in the future. Then return userId.
cache[name] = userId
return userId
end
-- If here, 'success' was false, meaning GetUserIdFromNameAsync()
-- was unable to find the 'userId' for the 'name' provided. We can warn the
-- user this happened and then return nothing, or nil.
warn("Unable to find UserId for Name:", name)
return nil
end
-- Example Data:
-- UserId: 118271 Name: "RobloxRulez"
-- UserId: 131963979 Name: "docsRule"
-- The first time a Name is used, GetUserIdFromNameAsync() will be called
local userIdOne = getUserIdFromName("RobloxRulez")
local userIdTwo = getUserIdFromName("docsRule")
-- Because "RobloxRulez" was previously used, get its UserId from the cache
local userIdOneQuick = getUserIdFromName("RobloxRulez")
print(userIdOne, userIdTwo, userIdOneQuick)
-- prints: "118271 131963979 118271"Get User Thumbnail Async
Players: Get User Thumbnail Async(
Parameters
Returns
Code Samples
Display Player Thumbnail
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local PLACEHOLDER_IMAGE = "rbxassetid://0" -- replace with placeholder image
-- fetch the thumbnail
local userId = player.UserId
local thumbType = Enum.ThumbnailType.HeadShot
local thumbSize = Enum.ThumbnailSize.Size420x420
local content, isReady = Players:GetUserThumbnailAsync(userId, thumbType, thumbSize)
-- set the ImageLabel's content to the user thumbnail
local imageLabel = script.Parent
imageLabel.Image = (isReady and content) or PLACEHOLDER_IMAGE
imageLabel.Size = UDim2.fromOffset(420, 420)player From Character
players
Set Chat Style
Parameters
| Default Value: Classic |
Returns
()
Code Samples
Setting a Player's Chat Style
-- Command bar
game:GetService("Players"):SetChatStyle(Enum.ChatStyle.Classic) -- Set's chat style to Classic
-- LocalScript
local Players = game:GetService("Players")
Players:SetChatStyle(Enum.ChatStyle.Classic) -- ErrorsTeam Chat
Parameters
Returns
()
Code Samples
Sending Team Chat
-- Command bar
game:GetService("Players"):TeamChat("Hello World") -- Sends a "Hello World" message to all players on the local player's team
-- LocalScript
local Players = game:GetService("Players")
Players:TeamChat("Hello World") -- ErrorsUnban Async
Parameters
Returns
()
Code Samples
Unbanning Users
local Players = game:GetService("Players")
local function shouldBeUnbanned(player: Player): boolean
-- Replace with your own logic
return true
end
Players.PlayerAdded:Connect(function(player)
if shouldBeUnbanned(player) then
local config: UnbanConfigType = {
UserIds = { player.UserId, 789 },
ApplyToUniverse = false,
}
local success, err = pcall(function()
return Players:UnbanAsync(config)
end)
print(success, err)
end
end)Events
Player Added
Parameters
Code Samples
Players.PlayerAdded
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print("A player has entered: " .. player.Name)
end
Players.PlayerAdded:Connect(onPlayerAdded)Player Membership Changed
Parameters
Code Samples
Handling Premium Membership Changes
local Players = game:GetService("Players")
local function grantPremiumBenefits(player)
-- Grant the player access to Premium-only areas, items, or anything you can imagine!
print("Giving", player, "premium benefits!")
end
local function playerAdded(player)
if player.MembershipType == Enum.MembershipType.Premium then
grantPremiumBenefits(player)
end
end
local function playerMembershipChanged(player)
print("Received event PlayerMembershipChanged. New membership = " .. tostring(player.MembershipType))
if player.MembershipType == Enum.MembershipType.Premium then
grantPremiumBenefits(player)
end
end
Players.PlayerAdded:Connect(playerAdded)
Players.PlayerMembershipChanged:Connect(playerMembershipChanged)Player Removing
Parameters
Code Samples
Players.PlayerRemoving
local Players = game:GetService("Players")
local function onPlayerRemoving(player)
print("A player has left: " .. player.Name)
end
Players.PlayerRemoving:Connect(onPlayerRemoving)User Subscription Status Changed