Player

Show Deprecated

A Player object 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 Player.UserId since it is possible that a player can change their username.

There are several similar methods in the Players for working with Player objects. Use these over their respective Instance methods:

Code Samples

Leaderstats

1local Players = game:GetService("Players")
2
3local function onPlayerAdded(player)
4 -- Create a container for leaderstats
5 local leaderstats = Instance.new("Folder")
6 leaderstats.Name = "leaderstats"
7
8 -- Create one leaderstat value
9 local vScore = Instance.new("IntValue")
10 vScore.Name = "Score"
11 vScore.Value = 0
12 vScore.Parent = leaderstats
13
14 -- Add to player (displaying it)
15 leaderstats.Parent = player
16end
17
18Players.PlayerAdded:Connect(onPlayerAdded)

Summary

Properties

Describes the player's account age in days.

READ ONLY
NOT REPLICATED

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 desktop version of Roblox.

Determines player's character movement mode when using a desktop version of Roblox.

Determines if the player can toggle mouse lock.

Determines player's camera movement mode when using a touch device.

Determines player's character movement mode when using a touch device.

The DisplayName of the UserId associated with the Player.

Describes the user ID of the player who was followed into a game by a player.

READ ONLY
NOT REPLICATED

Whether player client-side gameplay is currently paused.

Sets the distance at which this player will see other Humanoid's health bars. If set to 0, the health bars will not be displayed.

Describes the account's membership type.

READ ONLY
NOT REPLICATED

Sets the distance at which this player will see other Humanoid's names. If set to 0, names are hidden.

Determines whether the player is on a specific team.

Sets the part to focus replication around.

If set, the player will respawn at the given SpawnLocation.

Determines the Team with which a Player is associated.

NOT REPLICATED

Determines the Team with which a Player is associated.

A unique identifying integer assigned to all user accounts.

Events


Fired when a player's character spawns or respawns.


Fires when the the full appearance of a Player's Player.Character has been inserted.


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.


Usually fired two minutes after the game engine classes the player as idle. Time is the amount of seconds since this point.

OnTeleport(teleportState: TeleportState, placeId: number, spawnName: string): RBXScriptSignal  

Fired when the TeleportState of a player changes.

Methods

AddToBlockList(userIds: Array): nil  



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 point. Returns 0 if the player has no character.


Returns a dictionary containing information describing how the Player joins the experience.


Returns the mouse being used by the client.


Returns the engine-calculated latency in seconds.


Returns whether or not the appearance of the player's character has loaded.

Kick(message: string): nil  

Forcibly disconnect a player from the game, optionally providing a message.

Move(walkDirection: Vector3, relativeToCamera: boolean): nil  

Causes the player's character to walk in the given direction until stopped, or interrupted by the player (by using their controls).


Removes the player's character.

SetAccountAge(accountAge: number): nil  

Sets the AccountAge of the player.

SetMembershipType(membershipType: MembershipType): nil  


SetModerationAccessKey(moderationAccessKey: string): nil  



Sets whether or not the player sees filtered chats, rather than normal chats.

UpdatePlayerBlocked(userId: number, blocked: boolean): nil  


GetFriendsOnline(maxFriends: number): Array  YIELDS

Returns a dictionary of online friends.

GetRankInGroup(groupId: number): number  YIELDS

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.

GetRoleInGroup(groupId: number): string  YIELDS

Returns the player's role in the group as a string, or "Guest" if the player isn't part of the group.

IsFriendsWith(userId: number): boolean  YIELDS

Checks whether a player is a friend of the user with the given Player.UserId.

IsInGroup(groupId: number): boolean  YIELDS

Checks whether a player is a member of a group with the given ID.

LoadCharacter(): nil  YIELDS

Creates a new character for the player, removing the old one. Also clears the player's Backpack and PlayerGui.


Functions similar to Player:LoadCharacter(), but the request is processed synchronously instead of asynchronously.


Spawns an avatar so it has everything equipped in the passed in HumanoidDescription.

RequestStreamAroundAsync(position: Vector3, timeOut: number): nil  YIELDS

Requests that the server stream to the player around the specified location.

Properties

AccountAge

Read Only
Not Replicated

The AccountAge is a Player property that describes how long ago a player's account was registered in days. It is set using the Player:SetAccountAge() function, which cannot be accessed by scripts.

This property is useful for conditionally showing new Roblox players content such as tutorials.

AutoJumpEnabled

The AutoJumpEnabled property determines whether the Player.Character of a Player using a mobile device will automatically jump when they hit an obstacle. This can make levels more navigable while on a mobile device.

When the player joins the game, the StarterPlayer.AutoJumpEnabled value determines the initial state of this property. Then, this property determines the value of the Humanoid.AutoJumpEnabled property of the Player.Characters Humanoid on spawn. In other words, it is possible to set the auto-jump behavior on a per-character, per-player and per-game basis using these three properties.

CameraMaxZoomDistance

The CameraMaxZoomDistance Player property sets the maximum distance in studs the camera can be from the character with the default cameras.

In other words, it controls the maximum distance the player's camera is allowed to zoom out.

The default value of this property is set by StarterPlayer.CameraMaxZoomDistance. If this value is set to a lower value than Player.CameraMinZoomDistance, it will be increased to CameraMinZoomDistance.

CameraMinZoomDistance

The CameraMinZoonDistance Player property sets the minimum distance in studs the camera can be from the character with the default cameras.

In other words, it controls the minimum distance the player's camera is allowed to zoom in.

The default value of this property is set by StarterPlayer.CameraMinZoomDistance. If this value is set to a higher value than Player.CameraMaxZoomDistance it will be decreased to CameraMaxZoomDistance.

CameraMode

The CameraMode Player property sets what mode that the player's camera is in. By default, the camera mode is set to third person.

The camera has two modes:

  1. First person
  2. Third person

The CameraMode Enum is used to set CameraMode in Player, and determines when first and third person cameras should be used.

First-person

In first-person mode, the player's camera is zoomed all the way in. Unless there is a visible GUI present with the GuiButton.Modal property set to true, the mouse will be locked and the user's camera will turn as the mouse moves. First Person CameraMode

Third-person

In third-person mode, the character can be seen in the camera. While in third-person mode on Roblox:

  • You may right-click and drag to rotate your camera, or use the arrow keys at the bottom right-hand corner of the screen.
  • When you move your mouse, your camera does not change (unless you move the mouse to the end of the screen).
  • When you press any of the arrow keys, the user's character will face in the corresponding arrow key's direction.
  • You can zoom in and out freely.

Third-person is the default camera setting. Third Person CameraMode

Note

  • This item should be used in a LocalScript to work as expected online.

CanLoadCharacterAppearance

The CanLoadCharacterAppearance Player property determines whether the character's appearance will be loaded when the player spawns. The default value of this property is set by StarterPlayer.LoadPlayerAppearance.

If true, the character will load the appearance of the player corresponding to the player's Player.CharacterAppearanceId.

If false, the player will spawn with a default appearance - a grey character model without any hats, shirts, pants, etc.

Attempting to set the property after the character has spawned will not change the character, you must call Player:LoadCharacter() to load the new appearance.

Character

The Character property contains a reference to a Model containing a Humanoid, body parts, scripts and other objects required for simulating the player's avatar in-game. The model is parented to the Workspace, but may be moved. It is automatically loaded when Players.CharacterAutoLoads is true, but can be manually loaded otherwise using Player:LoadCharacter().

Initially, this property is nil then set when the player's character first spawns. Use the Player.CharacterAdded event to detect when a player's character properly loads, and the Player.CharacterRemoving event to detect when the character is about to despawn. Avoid using Instance:GetPropertyChangedSignal() on this property.

Note: LocalScripts that are cloned from StarterGui or StarterPack into a player's Backpack or PlayerGui are often run before the old Character model is deleted. Player.Character still refers to a model, but that model's parent is nil and it has been destroyed. Because of this, if the Character already exists, you should check to make sure that the Character's parent is not nil before using it.

So if you're writing a LocalScript under the StarterGui or StarterPack that requires access to the player's character, use this:


1local Players = game:GetService("Players")
2local player = Players.LocalPlayer
3local character = player.Character
4if not character or not character.Parent then
5 character = player.CharacterAdded:wait()
6end
7

CharacterAppearanceId

This property determines the user ID of the account whose character appearance is used for a player's character. By default, this property is the Class.Player's Class.Player.UserId`, which uses the player's avatar as they have created it on the Roblox website.

Changing this property to the user ID of another account will cause the player to spawn with that account's appearance (hats, shirt, pants, etc).

Games can also toggle whether or not a player's character appearance is loaded in game by changing the StarterPlayer.LoadCharacterAppearance property.

DevCameraOcclusionMode

The DevCameraOcclusionMode Player property sets how the default camera handles objects between the camera and the player. Set by default by StarterPlayer.DevCameraOcclusionMode.

The default value is Zoom (0): The camera will zoom in until there is nothing between the player and camera.

See DevCameraOcclusionMode for the different occlusion modes available. Sets how the default camera handles objects between the camera and the player.

DevComputerCameraMode

The DevComputerCameraMode property determines the manner in which a player moves their camera when using a mouse-and-keyboard device device. See DevComputerCameraMovementMode for a description of each camera control mode 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 by StarterPlayer.DevComputerCameraMovementMode.

Note

  • The word "Computer" in this property name refers to non-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 is a good idea to allow players to choose their control mode to maximize accessibility.
  • It is possible to create a custom control scheme by setting this property to Scriptable.
  • This property does not affect players using a touch enabled device. See Player.DevTouchCameraMode instead.

DevComputerMovementMode

The DevComputerMovementMode property determines the manner in which a player moves their character when using a mouse-and-keyboard device device. See DevComputerMovementMode for a description of each movement control mode 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 by StarterPlayer.DevComputerMovementMode.

Note

  • The word "Computer" in this property name refers to non-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 a good idea to allow players to choose their control mode to maximize accessibility.
  • It is possible to create a custom control scheme by setting this property to Scriptable.
  • This property does not affect players using a touch enabled device. See Player.DevTouchMovementMode instead.

DevEnableMouseLock

This property determines if a player is able to toggle mouse lock by pressing Shift. A player can disable the mouse lock switch in Roblox's game settings. By default, this property is set to the value of StarterPlayer.EnableMouseLockOption. This can be set server-side during run-time by using a Script. It can not be set client-side.

What is Mouse Lock?

When mouse lock is enabled, the player's cursor is locked to the center of the screen. Moving the mouse will orbit the camera around the player's character, and character will face the same direction as the camera. It also offsets the camera view just over the right shoulder of the player's character.

Below, the camera is moved left and right first by holding right-click. Then, mouse lock is enabled which changes the mouse to a target reticule, and offsets the camera. The camera is again moved left and right (without holding right click).

DevTouchCameraMode

The DevTouchCameraMode property determines the manner in which a player moves their camera when using a TouchEnabled device. See DevTouchCameraMovementMode for a description of each camera control mode 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 by StarterPlayer.DevTouchCameraMovementMode.

Note

  • When set to UserChoice, a player can choose between any control mode (except Scriptable) in the Roblox game settings. In general, it is a good idea to allow players to choose their control mode to maximize accessibility.
  • It is possible to create a custom control scheme by setting this property to Scriptable.
  • This property does not affect players who are not using a touch enabled device. See Player.DevComputerCameraMovementMode instead.

DevTouchMovementMode

The DevTouchMovementMode property determines the manner in which a player moves their character when using a TouchEnabled device. See DevTouchMovementMode for a description of each movement control mode 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 by StarterPlayer.DevTouchMovementMode.

Note

  • When set to UserChoice, a player can choose between any control mode (except Scriptable) in the Roblox game settings. In general, it is a good idea to allow players to choose their control mode to maximize accessibility.
  • It is possible to create a custom control scheme by setting this property to Scriptable.
  • This property does not affect players who are not using a touch enabled device. See Player.DevComputerMovementMode instead.

DisplayName

The DisplayName is a Player property that contains the display name of the authenticated user associated with the Player object. Unlike usernames, display names are non-unique names a player displays to others. If the Roblox user has not chosen one, the property will read the same as the Name property.

Note:

  • Since display names are non-unique, it's possible for two players in a single instance to have identical names. If you need a globally unique identifier for a player, use Player.UserId (which is static) or Player.Name (which is the current Username) instead.
  • Characters generated with LoadCharacter or by the Roblox engine will have their Humanoid's DisplayName property assigned to the Player's DisplayName property.
  • Display names may have unicode characters in the string. See UTF-8 for more information on how to work with strings with unicode characters.

FollowUserId

Read Only
Not Replicated

The FollowUserId is a Player property that contains the Player.UserId of the user that a player followed into the game. If the player did not follow anyone into the game, this property will be 0. This property is useful for alerting players who have been followed by another player into the game.

You can get the name of the player followed using this user ID and the Players:GetNameFromUserIdAsync() function.

GameplayPaused

The GameplayPaused property indicates if the player is currently in a pause state in a place with StreamingEnabled activated. It is set on the client but replicated to the server. To determine the pause status, you can utilize this property.

See also:

HealthDisplayDistance

The HealthDisplayDistance Player property sets the distance in studs at which this player will see other Humanoid's health bars. If set to 0, the health bars will not be displayed. This property is set to StarterPlayer.HealthDisplayDistance by default.

Note

If a Humanoid's health bar is visible, you can set the display type using Humanoid.DisplayDistanceType.

MembershipType

Read Only
Not Replicated

The MembershipType Player property can be used to determine the membership type of the player. It holds a MembershipType enum of the account's membership type.

This property can only be read from to determine membership (it cannot be set to another membership type). The property can only be changed via CoreScripts using Player:SetMembershipType() - which are not accessible.

NameDisplayDistance

The NameDisplayDistance StarterPlayer property sets the distance in studs at which this player will see other Humanoid's names. If the property is set to 0, names are hidden. This property is set to StarterPlayer.NameDisplayDistance by default.

Note

If a Humanoid's health bar is visible, you can set the display type using Humanoid.DisplayDistanceType.

Neutral

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 that the Player.Team property will be nil and the Player.TeamColor will be white.
  • When false, the player is on a specific team. The Player.Team property will correspond to the Team that the player is on, as will the Player.TeamColor.

ReplicationFocus

The ReplicationFocus Player property sets the part to focus replication around a Player. Different Roblox systems that communicate over the network (such as physics, streaming, etc) replicate at different rates depending on how close objects are to the replication focus.

When this property is nil, it reverts to its default behavior which is to treat the local player's character's PrimaryPart as the replication focus.

This property should only be set on the server with a Script, not a LocalScript. Note that this property does not change or update network ownership of parts.

RespawnLocation

If set, the player will respawn at the given SpawnLocation. This property can only be set through Lua and must contain a reference to a valid SpawnLocation, which must meet the following criteria:

If RespawnLocation is not set to a valid SpawnLocation then the default spawning logic will apply. For more information on this see the page for SpawnLocation.

Alternatives to RespawnLocation

Team

Not Replicated

The Team property is a reference to a Team object within the Teams service. It determines the team the player is on; if the Player isn't on a team or has an invalid Player.TeamColor, this property is nil. When this property is set, the player has joined the Team and the Team.PlayerAdded event fires on the associated team. Similarly, Team.PlayerRemoved fires when the property is unset from a certain Team.

TeamColor

The TeamColor property determines which team a Player is associated with according to that Team's Team.TeamColor. Changing this property will change Player.Team according to whichever team has the same BrickColor for their Team.TeamColor. If no Team object has the associated TeamColor, the player will not be associated with a team.

It's often a better idea to set Player.Team to the respective Team instead of using this property. Setting this property often leads to repetition of the same BrickColor value for a certain teams across many scripts; this is something you want to avoid when adhering to the don't-repeat-yourself principle.

UserId

The UserId is a Player property that contains a read-only integer that uniquely and consistently identifies every user account on Roblox. Unlike the Instance.Name of a Player, which may change according the user's present username, this value will never change for the same account.

This property is essential when saving/loading player data using GlobalDataStores. Use a player's UserId as the data store key so that each player has a unique key.

Events

CharacterAdded

The CharacterAdded event fires when a player's character spawns (or respawns). This event fires soon after setting Player.Character to a non-nil value or calling Player:LoadCharacter(), which is before 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 fire many times as players die then respawn in a place. If you want to detect when a player joins or leaves the game, use the Players.PlayerAdded and Players.PlayerRemoving events instead.

Note that the Humanoid and its default body parts (head, torso, and limbs) will exist when this event fires, but clothing items like Hats and Shirts, and Pants may take a few seconds to be added to the character. Connect Instance.ChildAdded on the added character to detect these, or wait for the Player.CharacterAppearanceLoaded event to be sure the character has everything equipped.

Parameters

character: Model

An instance of the character that spawned/respawned.


Code Samples

Accessory Remover

1local Players = game:GetService("Players")
2local RunService = game:GetService("RunService")
3
4local function destroyAccessory(object)
5 if object:IsA("Hat") or object:IsA("Accessory") then
6 object:Destroy()
7 end
8end
9
10local function onCharacterAdded(character)
11 -- Wait a brief moment before removing accessories to avoid the
12 -- "Something unexpectedly set ___ parent to NULL" warning
13 RunService.Stepped:Wait()
14 -- Check for any existing accessories in the player's character
15 for _, child in pairs(character:GetChildren()) do
16 destroyAccessory(child)
17 end
18 -- Hats may be added to the character a moment after
19 -- CharacterAdded fires, so we listen for those using ChildAdded
20 character.ChildAdded:Connect(destroyAccessory)
21end
22
23local function onPlayerAdded(player)
24 player.CharacterAdded:Connect(onCharacterAdded)
25end
26
27Players.PlayerAdded:Connect(onPlayerAdded)
Respawn at Despawn Location

1local Players = game:GetService("Players")
2local RunService = game:GetService("RunService")
3
4-- This table maps "Player" objects to Vector3
5local respawnLocations = {}
6
7local function onCharacterAdded(character)
8 local player = Players:GetPlayerFromCharacter(character)
9 -- Check if we saved a respawn location for this player
10 if respawnLocations[player] then
11 -- Teleport the player there when their HumanoidRootPart is available
12 local hrp = character:WaitForChild("HumanoidRootPart")
13 -- Wait a brief moment before teleporting, as Roblox will teleport the
14 -- player to their designated SpawnLocation (which we will override)
15 RunService.Stepped:wait()
16 hrp.CFrame = CFrame.new(respawnLocations[player] + Vector3.new(0, 3.5, 0))
17 end
18end
19
20local function onCharacterRemoving(character)
21 -- Get the player and their HumanoidRootPart and save their death location
22 local player = Players:GetPlayerFromCharacter(character)
23 local hrp = character:FindFirstChild("HumanoidRootPart")
24 if hrp then
25 respawnLocations[player] = hrp.Position
26 end
27end
28
29local function onPlayerAdded(player)
30 -- Listen for spawns/despawns
31 player.CharacterAdded:Connect(onCharacterAdded)
32 player.CharacterRemoving:Connect(onCharacterRemoving)
33end
34
35local function onPlayerRemoved(player)
36 -- Forget the respawn location of any player who is leaving; this prevents
37 -- a memory leak if potentially many players visit
38 respawnLocations[player] = nil
39end
40
41-- Note that we're NOT using PlayerRemoving here, since CharacterRemoving fires
42-- AFTER PlayerRemoving, we don't want to forget the respawn location then instantly
43-- save another right after
44Players.PlayerAdded:Connect(onPlayerAdded)
45Players.ChildRemoved:Connect(onPlayerRemoved)
Detecting Player Spawns and Despawns

1local Players = game:GetService("Players")
2
3local function onCharacterAdded(character)
4 print(character.Name .. " has spawned")
5end
6
7local function onCharacterRemoving(character)
8 print(character.Name .. " is despawning")
9end
10
11local function onPlayerAdded(player)
12 player.CharacterAdded:Connect(onCharacterAdded)
13 player.CharacterRemoving:Connect(onCharacterRemoving)
14end
15
16Players.PlayerAdded:Connect(onPlayerAdded)

CharacterAppearanceLoaded

This event fires when the the full appearance of a Player's Player.Character has been inserted.

Player.Character's generally have a range of objects modifying their appearance including Accoutrements, Shirts, Pants and CharacterMeshes. This event will fire when all such objects have been inserted into the Player.Character.

One use for this event, is to remove and save aspects of a Characters appearance to be used later. See below for an example of this.

Parameters


Code Samples

Remove and Return Hats

1local Players = game:GetService("Players")
2
3local function playerAdded(player)
4 player.CharacterAppearanceLoaded:Connect(function(character)
5 local humanoid = character:WaitForChild("Humanoid")
6
7 -- save hats for later
8 local accessories = {}
9 for _, accessory in pairs(humanoid:GetAccessories()) do
10 table.insert(accessories, accessory:Clone())
11 end
12
13 humanoid:RemoveAccessories()
14
15 task.wait(5)
16
17 -- make sure the player still exists, and has the same character
18 if player and player.Character and player.Character == character then
19 if humanoid:GetState() ~= Enum.HumanoidStateType.Dead then
20 for _, accessory in pairs(accessories) do
21 humanoid:AddAccessory(accessory)
22 end
23 end
24 end
25
26 accessories = nil
27 end)
28end
29
30for _, player in pairs(Players:GetPlayers()) do
31 playerAdded(player)
32end
33Players.PlayerAdded:Connect(playerAdded)

CharacterRemoving

The CharacterRemoving event fires right before a player's character is removed, 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, if you would like print a message every time a player spawns and dies:


1local Players = game:GetService("Players")
2
3local function onCharacterSpawned(player)
4 print(player.Name .. " is spawning")
5end
6
7local function onCharacterDespawned(player)
8 print(player.Name .. " is despawning")
9end
10
11local function onPlayerAdded(player)
12 player.CharacterAdded:Connect(function ()
13 onCharacterDespawned(player)
14 end)
15 player.CharacterRemoving:Connect(function ()
16 onCharacterDespawned(player)
17 end)
18end
19
20Players.PlayerAdded:Connect(onPlayerAdded)
21

This event is only concerned with the Character of a Player. If you instead need to track when a player joins/leaves the game, use the events Players.PlayerAdded and Players.PlayerRemoving.

Parameters

character: Model

An instance of the character that is being removed.


Code Samples

Player.CharacterRemoving

1game.Players.PlayerAdded:Connect(function(player)
2 player.CharacterRemoving:Connect(function(character)
3 print(character.Name .. " has died.")
4 end)
5end)

Chatted

The Chatted event fires when a Player types a message and presses enter in Roblox's provided chat bar. This is done using some Lua bindings by the default chat script. You can prevent players from chatting by using StarterGui:SetCoreGuiEnabled() and disabling the Chat CoreGuiType.

Chat Commands

Using this event and some string manipulation functions like string.sub() and string.lower(), it is possible to create chat commands, even with arguments like player names. Usually, commands are prefixed such as heal PlayerName. To check for a prefix in a string, use string.sub() on the message to check a substring of the message: string.sub(message, 1, 6) == "/heal " (note the inclusion of the space) . Then, extract the rest of the command using string.sub() again: string.sub(message, 7) will be equal to the player name. Check if that player exists, and if so, perform the command's action (in this example, healing them). Check the code samples for examples of chat commands.

Filtering

The message text fired with this event is unfiltered. If you are displaying player input like chat to other players in any form, it must be filtered using Chat:FilterStringAsync(). Keep this in mind when creating your own chat systems; if your game does not properly filter chat it 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 the intended target of the chat message.


Code Samples

Playing/Spectating Teams

1local Players = game:GetService("Players")
2local Teams = game:GetService("Teams")
3
4local teamPlaying = Teams.Playing
5local teamSpectators = Teams.Spectating
6
7local playCommand = "/play"
8
9local function play(player)
10 player.Team = teamPlaying
11 player.TeamColor = teamPlaying.TeamColor
12 -- Respawn the player (moves them to spawn location)
13 player:LoadCharacter()
14end
15
16local function onPlayerDied(player, _character)
17 -- When someone dies, put them on the spectator team
18 player.Team = teamSpectators
19end
20
21local function onPlayerSpawned(player, character)
22 local human = character:WaitForChild("Humanoid")
23 human.Died:Connect(function()
24 onPlayerDied(player, character)
25 end)
26end
27
28local function onPlayerChatted(player, message)
29 if message:sub(1, playCommand:len()):lower() == playCommand then
30 play(player)
31 end
32end
33
34local function onPlayerAdded(player)
35 if player.Character then
36 onPlayerSpawned(player, player.Character)
37 end
38 player.CharacterAdded:Connect(function()
39 onPlayerSpawned(player, player.Character)
40 end)
41 player.Chatted:Connect(function(message, _recipient)
42 onPlayerChatted(player, message)
43 end)
44end
45
46for _, player in pairs(Players:GetPlayers()) do
47 onPlayerAdded(player)
48end
49Players.PlayerAdded:Connect(onPlayerAdded)
Player.Chatted

1local Players = game:GetService("Players")
2
3local function onPlayerAdded(player)
4 local function onChatted(message)
5 -- do stuff with message and player
6 print(message)
7 end
8
9 player.Chatted:Connect(onChatted)
10end
11
12Players.PlayerAdded:Connect(onPlayerAdded)
Join Team Command

1local Players = game:GetService("Players")
2local Teams = game:GetService("Teams")
3
4-- Command to choose a team (note the trailing space)
5local joinCommand = "/jointeam "
6
7local function findTeamByName(name)
8 -- First, check for the exact name of a team
9 if Teams:FindFirstChild(name) then
10 return Teams[name]
11 end
12 -- Let's check for case-insensitive partial matches, like "red" for "Red Robins"
13 for _, team in pairs(Teams:GetChildren()) do
14 if team.Name:sub(1, name:len()):lower() == name:lower() then
15 return team
16 end
17 end
18 -- If we get to this point, no team matched the one we were looking for :(
19end
20
21local function onPlayerChatted(player, message, _recipient)
22 -- Note: string.sub(message, ...) is the same as message:sub(...)
23 if message:sub(1, joinCommand:len()):lower() == joinCommand:lower() then
24 -- Matched "/JOINTEAM xyz" to our join command prefix "/jointeam "
25 local teamName = message:sub(joinCommand:len() + 1) -- Cut out the "xyz" from "/jointeam xyz"
26 local team = findTeamByName(teamName)
27 if team then
28 -- Set the team!
29 player.Team = team
30 player.Neutral = false
31 else
32 -- Tell the player that team could not be found :(
33 player.Team = nil
34 player.Neutral = true
35 end
36 end
37end
38
39local function onPlayerAdded(player)
40 player.Chatted:Connect(function(...)
41 onPlayerChatted(player, ...)
42 end)
43end
44
45Players.PlayerAdded:Connect(onPlayerAdded)

FriendStatusChanged

Roblox Script Security

Parameters

player: Player
friendStatus: FriendStatus

Idled

This event is usually fired two minutes after the game engine classifies the player as idle. Time is the amount of seconds since this point.

This can be used to track when a player has been idled for approximately two minutes - which can be useful for implementing away from keyboard (AFK) features into a game.

When the game engine classifies a player as idle, this event is called after two minutes. After every check, if the player is still idled, the event will continue to fire until the check reveals the player is no longer idle.

This event is used by Roblox to automatically disconnect players that have been idle for at least 20 minutes. If you would like to track when this disconnect occurs, considering using Players.PlayerRemoving alongside this event.

Parameters

time: number

The time in seconds the player has been idle.


Code Samples

Player.Idled1

1local Players = game:GetService("Players")
2
3local function onPlayerAdded(player)
4 local function onIdled(time)
5 print("Player has been idle for " .. time .. " seconds")
6 end
7
8 player.Idled:Connect(onIdled)
9end
10
11Players.PlayerAdded:Connect(onPlayerAdded)

OnTeleport

Fired when the TeleportState of a player changes. This event is useful for detecting whether a teleportation was successful.

What is the TeleportState?

When a teleportation request is made using TeleportService, there are a series of stages before the Player is teleported. The current stage is represented by the TeleportState value which is given by OnTeleport. See below for a practical example of this.

Parameters

teleportState: TeleportState

The new TeleportState of the Player.

placeId: number

The ID of the place the Player is being teleported to.

spawnName: string

The name of the spawn to teleport to, if TeleportService:TeleportToSpawnByName() has been used.


Code Samples

Player.OnTeleport

1local Players = game:GetService("Players")
2
3Players.PlayerAdded:Connect(function(player)
4 local playerOnTeleport = player
5 player.OnTeleport:Connect(function(teleportState, _placeId, _spawnName)
6 if teleportState == Enum.TeleportState.Started then
7 print("Teleport started (" .. playerOnTeleport.Name .. ")")
8 elseif teleportState == Enum.TeleportState.WaitingForServer then
9 print("Teleport waiting for server (" .. playerOnTeleport.Name .. ")")
10 elseif teleportState == Enum.TeleportState.InProgress then
11 print("Teleport in progress (" .. playerOnTeleport.Name .. ")")
12 elseif teleportState == Enum.TeleportState.Failed then
13 print("Teleport failed! (" .. playerOnTeleport.Name .. ")")
14 end
15 end)
16end)

SimulationRadiusChanged

Local User Security

Fired when the Player's Player.SimulationRadius is changed.

What is the SimulationRadius?

Player.SimulationRadius determines the radius around the Player.Character in which physically simulated objects, for whom network ownership is set to automatic, are physically simulated by the Player. In cases where a BasePart or assembly is within multiple player's SimulationRadiuses, the closest player is chosen.

Player.SimulationRadius, measured in studs, starts at 10 and grows at a rate of 5% per second until it reaches Player.MaximumSimulationRadius.

Note:

Parameters

radius: number

The new value of Player.SimulationRadius.


Code Samples

How to View, Track, and Modify a Player's Simulation Radius

1local Players = game:GetService("Players")
2
3local player = Players.LocalPlayer
4
5-- Set the maximum simulation radius (default is 1000)
6player.MaximumSimulationsRadius = 800
7
8local change = -20
9while true do
10 change = change * -1
11 player.SimulationRadius = player.SimulationRadius + change
12 task.wait(5)
13end
14
15-- Print the updated simulation radius
16player.SimulationRadiusChanged:Connect(function(radius)
17 print("The new simulation radius is: " .. radius .. "studs")
18end)

Methods

AddToBlockList

Roblox Script Security

Parameters

userIds: Array

Returns

ClearCharacterAppearance

The ClearCharacterAppearance function removes all Accessory, Shirt, Pants, CharacterMesh, and BodyColors from the given player's Player.Character. In addition, it also removes the T-Shirt Decal on the player's torso. The character's body part colors and face will remain unchanged. This method does nothing if the player does not have a Character.

Note

It does not remove t-shirts, head meshes, or faces.


Returns

No return.

Code Samples

How to Clear a Character's Appearance

1local Players = game:GetService("Players")
2
3local player = Players.LocalPlayer
4
5local character = player.Character or player.CharacterAdded:Wait()
6
7local function onChildRemoved(child)
8 print(child.ClassName, "removed from character")
9end
10
11character.ChildRemoved:Connect(onChildRemoved)
12
13player:ClearCharacterAppearance()
14--> BodyColors removed from character
15--> ShirtGraphic removed from character
16--> Shirt removed from character
17--> Pants removed from character
18--> CharacterMesh removed from character
19--> Hat removed from character
20--> Shirt removed from character

DistanceFromCharacter

The DistanceFromCharacter Player function returns the distance between the character's head and the given Vector3 point. It returns 0 if the player has no Player.Character.

This is useful when determining the distance between a player and another object or location in game.

Note

If you would like to determine the distance between two non-player instances or positions, you can use the following:


1local distance = (position1 - position2).magnitude
2

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

1local Players = game:GetService("Players")
2
3for _, player in pairs(Players:GetPlayers()) do
4 print(player:DistanceFromCharacter(Vector3.new(0, 0, 0)))
5end

GetFriendStatus

Roblox Script Security

Parameters

player: Player

GetGameSessionID

Roblox Security

Returns

GetJoinData

Returns a dictionary containing information describing how the Player joins 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 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 this method returns includes the player's teleport data. The Player:GetJoinData() method can only be used to fetch teleport data on the server. To fetch the data on the client, use TeleportService:GetLocalPlayerTeleportData().

Unlike TeleportService:GetLocalPlayerTeleportData(), Player:GetJoinData() only provides teleport data that meets the following security criteria:

  • It's guaranteed to have been sent by a Roblox server in the past 48 hours.
  • It's guaranteed to have been sent with this Player.
  • The SourcePlaceId and SourceGameId are guaranteed to be the place and universe the data was sent from. This means you can verify the teleport data came from an approved place.

As this data is transmitted by the client, it can still potentially be abused by an exploiter. Sensitive data such as player currency should be transmitted via a secure solution like Memory Stores.

LaunchData

Contains the string embedded in the launchData URL parameter that the user clicked to join the experience. Only available on the first join. If the user teleports to another server, the data isn't included. If you need the data after a teleport, forward it manually as teleport data. You can only include 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 characters such as spaces must be URL encoded using HttpService:UrlEncode() and are automatically decoded when the user joins the game. The decoded launch data can't exceed 200 bytes. You can store more complex data as a JSON string and decode it with HttpService:JSONDecode() on the server.

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 roblox downloaded on their mobile devices by using the AppsFlyer version of the link. 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 with ro.blox.com/Ebh5? and append the af_dp and af_web_dp parameters with the URL encoded version of Link 1.

Don't store confidential information in the LaunchData because it's fully visible in the URL. Furthermore, the data might not be authentic because a user can modify the URL.


Returns

A dictionary containing PlaceId and UserId values (see table in description).

Code Samples

Server TeleportData Example

1local Players = game:GetService("Players")
2
3local approvedPlaceIds = { 1 } -- insert approved PlaceIds here
4
5local function isPlaceIdApproved(placeId)
6 for _, id in pairs(approvedPlaceIds) do
7 if id == placeId then
8 return true
9 end
10 end
11 return false
12end
13
14local function onPlayerAdded(player)
15 local joinData = player:GetJoinData()
16
17 -- verify this data was sent by an approved place
18 if isPlaceIdApproved(joinData.SourcePlaceId) then
19 local teleportData = joinData.TeleportData
20 if teleportData then
21 local currentLevel = teleportData.currentLevel
22 print(player.Name .. " is on level " .. currentLevel)
23 end
24 end
25end
26
27Players.PlayerAdded:Connect(onPlayerAdded)
Decoding JSON Launch Data

1local HttpService = game:GetService("HttpService")
2local Players = game:GetService("Players")
3
4local function onPlayerAdded(player)
5 local launchData = player:GetJoinData().LaunchData
6 if launchData then
7 -- attempt to decode the data
8 local success, result = pcall(HttpService.JSONDecode, HttpService, launchData)
9 if success then
10 print(player.Name, "joined with data:", result)
11 else
12 -- this is probably due to the user messing with the URL
13 warn("Failed to parse launch data:" .. result)
14 end
15 end
16end
17
18Players.PlayerAdded:Connect(onPlayerAdded)
Referral URL Generator

1local Players = game:GetService("Players")
2
3local player = Players.LocalPlayer
4
5local DIRECT_JOIN_URL = "https://www.roblox.com/games/start?placeId=%d&launchData=%s"
6
7local textBox = script.Parent
8
9local function generateReferralURL(player)
10 return DIRECT_JOIN_URL:format(
11 game.PlaceId,
12 player.UserId
13 )
14end
15
16local function highlightAll()
17 if -- avoid recursive property updates
18 textBox:IsFocused()
19 and not (
20 textBox.SelectionStart == 1
21 and textBox.CursorPosition == #textBox.Text + 1
22 )
23 then
24 textBox.SelectionStart = 1
25 textBox.CursorPosition = #textBox.Text + 1
26 end
27end
28
29textBox.Focused:Connect(highlightAll)
30textBox:GetPropertyChangedSignal("SelectionStart"):Connect(highlightAll)
31textBox:GetPropertyChangedSignal("CursorPosition"):Connect(highlightAll)
32
33textBox.TextEditable = false
34textBox.ClearTextOnFocus = false
35
36textBox.Text = generateReferralURL(player)
Using a Table as Launch Data

1local HttpService = game:GetService("HttpService")
2
3local DATA_CHARACTER_LIMIT = 200
4
5local function encodeTableAsLaunchData(data)
6 -- convert the table to a string
7 local jsonEncodedData = HttpService:JSONEncode(data)
8
9 if #jsonEncodedData <= DATA_CHARACTER_LIMIT then
10 -- escape potentially invalid characters, such as spaces
11 local urlEncodedData = HttpService:UrlEncode(jsonEncodedData)
12 return true, urlEncodedData
13 else
14 -- report character limit error
15 return false, ("Encoded table exceeds %d character limit"):format(DATA_CHARACTER_LIMIT)
16 end
17end
18
19local sampleData = {
20 joinMessage = "Hello!";
21 urlCreationDate = os.time();
22 magicNumbers = {
23 534;
24 1337;
25 746733573;
26 };
27}
28
29local success, encodedData = encodeTableAsLaunchData(sampleData)
30
31if success then
32 print(encodedData)
33else
34 warn("failed to encode launch data: " .. encodedData)
35end
Tracking Traffic Sources

1local DataStoreService = game:GetService("DataStoreService")
2local Players = game:GetService("Players")
3
4local analyticsStore = DataStoreService:GetDataStore("Analytics")
5
6local ALLOWED_SOURCES = {
7 "twitter";
8 "youtube";
9 "discord";
10}
11
12local function onPlayerAdded(player)
13 local source = player:GetJoinData().LaunchData
14 -- check if the provided source is valid
15 if source and table.find(ALLOWED_SOURCES, source) then
16 -- update the data store to track the source popularity
17 local success, result = pcall(analyticsStore.IncrementAsync, analyticsStore, source)
18
19 if success then
20 print(player.Name, "joined from", source, "- total:", result)
21 else
22 warn("Failed to record join source: " .. result)
23 end
24 end
25end
26
27Players.PlayerAdded:Connect(onPlayerAdded)

GetMouse

The GetMouse Player function returns the Mouse being used by the client. The player's mouse instance can be used to track user mouse input including left and right mouse button clicks and movement and location.

The UserInputService service provides additional functions and events to track user input - especially for devices that do not use a mouse.

Note:

  • This item must be used in a LocalScript to work as expected online.
  • Following an update in July 2014, the mouse's icon can now be set with this method.

Returns

Code Samples

How to Track Mouse Input

1local Players = game:GetService("Players")
2
3local player = Players.LocalPlayer
4
5local mouse = player:GetMouse()
6
7local function onButton1Down()
8 print("Button 1 is down")
9end
10
11mouse.Button1Down:Connect(onButton1Down)

GetNetworkPing

GetNetworkPing returns the engine-calculated latency of the Player in seconds. "Ping" is a measurement of the time taken for data to be sent from the client to the server, then back again. For client-side LocalScripts, this function may only be called on the LocalPlayer. This function is useful in identifying and debugging issues that occur in high-latency scenarios. It can also be used in masking latency, such as adjusting the speed of throwing animations for projectiles.


Returns

GetUnder13

Roblox Script Security

Returns

HasAppearanceLoaded

The HasAppearanceLoaded Player function returns whether or not the appearance 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 loaded after they first join the game, which can be tracked using the Players.PlayerAdded event.


Returns

A boolean indicating whether or not the appearance of the player's character has loaded.

Code Samples

Check if a Player's Appearance Has Loaded

1local Players = game:GetService("Players")
2
3local function onPlayerAdded(player)
4 local loaded = player:HasAppearanceLoaded()
5 print(loaded)
6
7 while not loaded do
8 loaded = player:HasAppearanceLoaded()
9 print(loaded)
10 task.wait()
11 end
12end
13
14Players.PlayerAdded:Connect(onPlayerAdded)

Kick

The Kick Player method allows a game to gracefully disconnect a client from the game and optionally provide a message to the disconnected player. This is useful for moderating abusive players. When used in conjunction with a DataStore, it is possible to create ban lists with expiration dates. Only allow specific whitelisted users whom you trust to trigger this method on other players.

When used from a LocalScript, only the local player's client can be kicked.

##Example When calling this method on a Player with no arguments, they will be disconnected from the server and receive the default message: This game has shut down.

Getting kicked without a message.

Calling this method on a player but providing a string as the first argument will replace this message with the contents of the string.

Getting kicked with a message.

Parameters

message: string

The message to show the player upon kicking.

Default Value: ""

Returns

No return.

Code Samples

Kick Command

1local Players = game:GetService("Players")
2
3local kickCommand = "/kick "
4
5local function onOwnerChatted(message)
6 if message:sub(1, kickCommand:len()):lower() == kickCommand:lower() then
7 local name = message:sub(kickCommand:len() + 1)
8 local playerToKick = Players:FindFirstChild(name)
9 if playerToKick then
10 playerToKick:Kick("You have been kicked by the owner.")
11 else
12 -- Couldn't find the player in question
13 end
14 end
15end
16
17local function onPlayerAdded(player)
18 -- Restrict this command to only the creator/owner
19 if player.UserId == game.CreatorId and game.CreatorType == Enum.CreatorType.User then
20 player.Chatted:Connect(onOwnerChatted)
21 end
22end
23
24Players.PlayerAdded:Connect(onPlayerAdded)

Move

The Move Player function causes the player's character to walk in the given direction until stopped, or interrupted by the player (by using their controls).

This is useful when scripting NPC Humanoids that move around a map - but are not controlled by an actual player's input.

Note that the function's second argument indicates whether the provided Vector3 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: boolean

A boolean indicating whether the player should move relative to the player's camera.

Default Value: "false"

Returns

No return.

Code Samples

Moving the Player Towards Their Camera

1game.Players.LocalPlayer:Move(Vector3.new(0, 0, -1), true)

RemoveCharacter

Local User Security

The RemoveCharacter Player function removes the player's character. It also clears the player's Backpack and PlayerGui. This is useful when you would like to temporarily remove a player's character.

To reload a players character after using this function, simply use the Player:LoadCharacter() function.

Note

  • This function does not remove a player from the game. It only removes their character. To remove a player from the game, you can use the Player:Kick() function.

Returns

No return.

Code Samples

How to Remove a Player's Character

1local Players = game:GetService("Players")
2
3local player = Players.LocalPlayer
4
5player:RemoveCharacter()
6task.wait(5)
7player:LoadCharacter()

RequestFriendship

Roblox Script Security

Parameters

player: Player

Returns

RevokeFriendship

Roblox Script Security

Parameters

player: Player

Returns

SetAccountAge

Plugin Security

The SetAccountAge function sets the Player.AccountAge of the player in days.

It is used to set the Player property that describes how long ago a player's account was registered in days.

This does not set the age of the player on the account, but the age of the account itself relative to when it was first created.

Parameters

accountAge: number

The age of the account in days.


Returns

No return.

Code Samples

Setting the Player's Account Age

1local Players = game:GetService("Players")
2
3local player = Players.LocalPlayer
4
5player:SetAccountAge(100)
Account Age Mark

1local Players = game:GetService("Players")
2
3local MAX_AGE_NEW_PLAYER = 7 -- one week
4local MIN_AGE_VETERAN = 365 -- one year
5
6-- This function marks a part with text using a BillboardGui
7local function mark(part, text)
8 local bbgui = Instance.new("BillboardGui")
9 bbgui.AlwaysOnTop = true
10 bbgui.StudsOffsetWorldSpace = Vector3.new(0, 2, 0)
11 bbgui.Size = UDim2.new(0, 200, 0, 50)
12 local textLabel = Instance.new("TextLabel")
13 textLabel.Size = UDim2.new(1, 0, 1, 0) -- Fill parent
14 textLabel.Text = text
15 textLabel.TextColor3 = Color3.new(1, 1, 1)
16 textLabel.TextStrokeTransparency = 0
17 textLabel.BackgroundTransparency = 1
18 textLabel.Parent = bbgui
19 -- Add to part
20 bbgui.Parent = part
21 bbgui.Adornee = part
22end
23
24local function onPlayerSpawned(player, character)
25 local head = character:WaitForChild("Head")
26 if player.AccountAge >= MIN_AGE_VETERAN then
27 mark(head, "Veteran Player")
28 elseif player.AccountAge <= MAX_AGE_NEW_PLAYER then
29 mark(head, "New Player")
30 else
31 mark(head, "Regular Player")
32 end
33end
34
35local function onPlayerAdded(player)
36 -- Listen for this player spawning
37 if player.Character then
38 onPlayerSpawned(player, player.Character)
39 end
40 player.CharacterAdded:Connect(function()
41 onPlayerSpawned(player, player.Character)
42 end)
43end
44
45Players.PlayerAdded:Connect(onPlayerAdded)

SetCharacterAppearanceJson

Roblox Script Security

Parameters

jsonBlob: string

Returns

SetMembershipType

Roblox Script Security

Parameters

membershipType: MembershipType

Returns

SetModerationAccessKey

Roblox Script Security

Parameters

moderationAccessKey: string

Returns

SetSuperSafeChat

Plugin Security

The SetSuperSafeChat Player function sets whether or not the player sees chat filtered by TextService's TextService:FilterStringAsync() rather than normal chats.

SuperSafeChat is a chat mode where player's cannot see unfiltered messages.

For example, entering the following command in the command prompt would enabled SuperSafeChat for the player named polarpanda16, as long as that player is in the game:

Command prompt example enabling SuperSafeChat.

Note

Regardless of whether a player has SuperSafeChat enabled, all chat should be filtered by TextService when broadcasted to other players or on the player's own screen. TextService:FilterStringAsync() returns a TextFilterResult object that can be filtered differently according to the message's intended use.

Parameters

value: boolean

A boolean indicating whether or not the player sees filtered chat.


Returns

No return.

Code Samples

Playing in Third Person

1local Players = game:GetService("Players")
2
3local player = Players.LocalPlayer
4
5player.CameraMode = Enum.CameraMode.Classic

UpdatePlayerBlocked

Roblox Script Security

Parameters

userId: number
blocked: boolean

Returns

GetFriendsOnline

Yields

This function returns a dictionary array of online friends, limited by the maxFriends value.

In the returned array, some fields are only present for certain location types. For example, PlaceId won't be present when LocationType is 0 (Mobile Website).

NameTypeDescription
VisitorIdnumberThe Player/UserId of the friend.
UserNamestringThe username of the friend.
DisplayNamestringThe `Class.Player.DisplayName|display name` of the friend.
LastOnlinestringWhen the friend was last online.
IsOnlinebooleanIf the friend is currently online.
LastLocationstringThe name of the friend's current location.
PlaceIdnumberThe place ID of the friend's last location.
GameIdstringThe DataModel/JobId of the friend's last location.
LocationTypenumber The location type of the friend's last location:
0Mobile Website
1Mobile InGame
2Webpage
3Studio
4InGame
5Xbox
6Team Create

Parameters

maxFriends: number

The maximum number of online friends to return. The default is 200.

Default Value: "200"

Returns

A dictionary of online friends (see the table above).

Code Samples

Get a List of Online Friends

1local Players = game:GetService("Players")
2
3local player = Players.LocalPlayer
4
5local success, result = pcall(player.GetFriendsOnline, player, 10)
6
7if success then
8 for _, friend in pairs(result) do
9 print(friend.UserName)
10 end
11else
12 warn("Failed to get online players: " .. result)
13end

GetRankInGroup

Yields

The GetRankInGroup Player function 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.

Note

Using this in a Script, as opposed to a LocalScript, will not get you the most up-to-date information. If a player leaves a group while they are in the game, GetRankInGroup will still think they're in that group until they leave. However, this does not happen when used with a LocalScript.

This is because the method caches results, so multiple calls of GetRankInGroup on the same player with the same group ID will yield the same 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 the same 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

1local Players = game:GetService("Players")
2
3local function onPlayerAdded(player)
4 if player:GetRankInGroup(2) == 255 then
5 print("Player is the owner of the group, 'LOL'!")
6 else
7 print("Player is NOT the owner of the group, 'LOL'!")
8 end
9end
10
11Players.PlayerAdded:Connect(onPlayerAdded)

GetRoleInGroup

Yields

The GetRoleInGroup Player function returns the player's role in the group as a string, or Guest if the player isn't part of the group.

Note

Using this in a Script, as opposed to a LocalScript, will not get you the most up-to-date information. If a player leaves a group while they are in the game, GetRoleInGroup will still think they're in that group until they leave. However, this does not happen when used with a LocalScript.

This is because the method caches results, so multiple calls of GetRoleInGroup on the same player with the same group ID will yield the same 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 the same 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 is not a member.

Code Samples

How to Check a Player's Role in a Group

1local Players = game:GetService("Players")
2
3local function onPlayerAdded(player)
4 print("Player is ranked as '", player:GetRoleInGroup(2), "' in group, 'LOL'!")
5end
6
7Players.PlayerAdded:Connect(onPlayerAdded)

IsFriendsWith

Yields

This function sends a request to the Roblox website asking whether a player is a friend of another user, given the Player.UserId of that user. This function caches results so multiple calls of the function on the same player with the same userId may not yield the most up-to-date result. This does not happen when used in a LocalScript.

Parameters

userId: number

The Player.UserId of the specified player.


Returns

A boolean indicating whether a player is a friend of the specified user.

Code Samples

How to Check if a Player is a Friend

1local Players = game:GetService("Players")
2
3local function onPlayerAdded(player)
4 if player:IsFriendsWith(146569) then
5 print(player.Name .. " is friends with gordonrox24!")
6 end
7end
8
9Players.PlayerAdded:Connect(onPlayerAdded)

IsInGroup

Yields

The IsInGroup Player function sends a request to the Roblox website asking whether a player is a member of a group, given the ID of that group.

Note

Using this in a Script, as opposed to a LocalScript, will not get you the most up-to-date information. If a player leaves a group while they are in the game, IsInGroup will still think they're in that group until they leave. However, this does not happen when used with a LocalScript.

This is because the method caches results, so multiple calls of IsInGroup on the same player with the same group ID will yield the same 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 the same cache as a 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

1local Players = game:GetService("Players")
2
3local function onPlayerAdded(player)
4 if player:IsInGroup(7) then
5 print("Player is in the Roblox Fan club!")
6 end
7end
8
9Players.PlayerAdded:Connect(onPlayerAdded)

LoadCharacter

Yields

The LoadCharacter Player function creates a new character for the player, removing the old one. It also clears the player's Backpack and PlayerGui.

This is useful in cases where you want to reload the character without killing the player, such as when you want to load a new character appearance after changing the player's Player.CharacterAppearance.

Note: The function is similar to Player:LoadCharacterBlocking(), but the request is processed asynchronously instead of synchronously. This means other tasks will be able to continue while the character is being loaded, including the rendering of the game and any other tasks. Also, this function can be used in script, while LoadCharacterBlocking cannot.

After calling LoadCharacter for an individual player, it is not recommended to call it again for the same player until after that player's Player.CharacterAppearanceLoaded event has fired.

Character Loading Event order

Calling the Player:LoadCharacter() with an R15 Avatar fires events in the following order (Note: R6 ordering is different):

  1. Player.Character sets
  2. Player.CharacterAdded fires
  3. Player.Changed fires with a value of "Character"
  4. Character appearance initializes
  5. Player.CharacterAppearanceLoaded fires
  6. Character.Parent sets to the DataModel
  7. The Character rig builds, and the Character scales
  8. Character moves to the spawn location
  9. LoadCharacter returns

Returns

No return.

Code Samples

Turn Off Auto-Loading and Simulate Character Respawn

1local Players = game:GetService("Players")
2
3local RESPAWN_DELAY = 5
4
5Players.CharacterAutoLoads = false
6
7local function onPlayerAdded(player)
8 local function onCharacterAdded(character)
9 local humanoid = character:WaitForChild("Humanoid")
10
11 local function onDied()
12 task.wait(RESPAWN_DELAY)
13 player:LoadCharacter()
14 end
15
16 humanoid.Died:Connect(onDied)
17 end
18
19 player.CharacterAdded:Connect(onCharacterAdded)
20
21 player:LoadCharacter()
22end
23
24Players.PlayerAdded:Connect(onPlayerAdded)

LoadCharacterBlocking

Yields
Local User Security

The LoadCharacterBlocking Player function is similar to Player:LoadCharacter(), but the request is processed synchronously instead of asynchronously.

This means that no other task will be able to continue until after the character has been loaded, including the rendering of the game and any other tasks.

Like LoadCharacter, this function creates a new character for the player, removing the old one. It also clears the player's Backpack and PlayerGui. This is useful in cases where you want to reload the character without killing the player, such as when you want to load a new character appearance after changing the player's Player.CharacterAppearance.

Note:

  • This function is used by Roblox's backend server when rendering avatar thumbnails.

Returns

No return.

Code Samples

How to Load a Player's Character

1local Players = game:GetService("Players")
2
3local USER_ID = 772462
4
5local player = Players.LocalPlayer
6
7player.CharacterAppearanceId = USER_ID
8player:LoadCharacterBlocking()

LoadCharacterWithHumanoidDescription

Yields

This function spawns an avatar so it has everything equipped in the passed in HumanoidDescription.

After calling LoadCharacterWithHumanoidDescription for an individual player, it is not recommended to call the function again for the same player until after that player's Player.CharacterAppearanceLoaded event has fired.

See also:

  • HumanoidDescription System, an article which explains the humanoid description system in greater detail and provides several scripting examples

Parameters

humanoidDescription: HumanoidDescription

A HumanoidDescription containing traits like body parts/colors, body scaling, accessories, clothing, and animations that will be equipped to the loaded character.


Returns

No return.

Code Samples

Spawn Characters With HumanoidDescription

1local Players = game:GetService("Players")
2
3Players.CharacterAutoLoads = false
4
5local function onPlayerAdded(player)
6 local humanoidDescription = Instance.new("HumanoidDescription")
7 humanoidDescription.HatAccessory = "2551510151,2535600138"
8 humanoidDescription.BodyTypeScale = 0.1
9 humanoidDescription.ClimbAnimation = 619521311
10 humanoidDescription.Face = 86487700
11 humanoidDescription.GraphicTShirt = 1711661
12 humanoidDescription.HeadColor = Color3.new(0, 1, 0)
13 player:LoadCharacterWithHumanoidDescription(humanoidDescription)
14end
15
16Players.PlayerAdded:Connect(onPlayerAdded)

RequestStreamAroundAsync

Yields

For games where StreamingEnabled is set to true, requests that the server stream to the player regions (parts and terrain) around the specified X, Y, Z location in the game world. It is useful if the game knows that the player's CFrame will be set to the specified location in the near future. Without providing the location with this call, the player may not have streamed in content for the destination, resulting in a streaming pause or other undesirable behavior.

The effect of this call will be temporary and there are no guarantees of what will be streamed in around the specified location. Client memory limits and network conditions may impact what will be available on the client.

Usage Precaution

Requesting streaming around an area is not a guarantee that the content will be present when the request completes, as streaming is affected by the client's network bandwidth, memory limitations, and other factors.

Parameters

position: Vector3

World location where streaming is requested.

timeOut: number

Optional timeout for the request.

Default Value: "0"

Returns

No return.