A newer version of the Gradio SDK is available: 6.12.0
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 Player.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.
Code Samples
This code sample demonstrates the creation of leaderboard stat values in Roblox's default player list UI. It creates a "Score" leaderstat that starts at 0.
Leaderstats
local Players = game:GetService("Players")
local function onPlayerAdded(player)
-- Create a container for leaderstats
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
-- Create one leaderstat value
local vScore = Instance.new("IntValue")
vScore.Name = "Score"
vScore.Value = 0
vScore.Parent = leaderstats
-- Add to player (displaying it)
leaderstats.Parent = player
end
Players.PlayerAdded:Connect(onPlayerAdded)
Summary
Properties
AccountAge: number
Describes the player's account age in days.
READ ONLY
NOT REPLICATED
AutoJumpEnabled: boolean
Determines whether the character of a player using a mobile device will automatically jump upon hitting an obstacle.
CameraMaxZoomDistance: number
The maximum distance the player's camera is allowed to zoom out.
CameraMinZoomDistance: number
The minimum distance the player's camera is allowed to zoom in.
CameraMode: CameraMode
Changes the camera's mode to either first or third person.
CanLoadCharacterAppearance: boolean
Determines whether the character's appearance will be loaded when the player spawns. If false, the player will spawn with a default appearance.
Character: Model
A Model controlled by the player that contains a Humanoid, body parts, scripts and other objects.
CharacterAppearanceId: number
Determines the user ID of the account whose character appearance is used for a player's character.
DevCameraOcclusionMode: DevCameraOcclusionMode
Sets how the default camera handles objects between the camera and the player.
DevComputerCameraMode: DevComputerCameraMovementMode
Determines player's camera movement mode when using a desktop version of Roblox.
DevComputerMovementMode: DevComputerMovementMode
Determines player's character movement mode when using a desktop version of Roblox.
DevEnableMouseLock: boolean
Determines if the player can toggle mouse lock.
DevTouchCameraMode: DevTouchCameraMovementMode
Determines player's camera movement mode when using a touch device.
DevTouchMovementMode: DevTouchMovementMode
Determines player's character movement mode when using a touch device.
DisplayName: string
The DisplayName of the UserId associated with the Player.
FollowUserId: number
Describes the user ID of the player who was followed into a game by a player.
READ ONLY
NOT REPLICATED
GameplayPaused: boolean
Whether player client-side gameplay is currently paused.
HasVerifiedBadge: boolean
Indicates if a player has a Verified Badge.
HealthDisplayDistance: number
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.
LocaleId: string
This property shows the locale id that the local player has set for their Roblox account.
HIDDEN
READ ONLY
NOT REPLICATED
MembershipType: MembershipType
Describes the account's membership type.
READ ONLY
NOT REPLICATED
NameDisplayDistance: number
Sets the distance at which this player will see other Humanoid's names. If set to 0, names are hidden.
Neutral: boolean
Determines whether the player is on a specific team.
ReplicationFocus: Instance
Sets the part to focus replication around.
RespawnLocation: SpawnLocation
If set, the player will respawn at the given SpawnLocation.
Team: Team
Determines the Team with which a Player is associated.
NOT REPLICATED
TeamColor: BrickColor
Determines the Team with which a Player is associated.
UserId: number
A unique identifying integer assigned to all user accounts.
Properties inherited from Instance
Archivable: boolean
Determines if an Instance can be cloned using Instance:Clone() or saved to file.
ClassName: string
A read-only string representing the class this Instance belongs to.
READ ONLY
NOT REPLICATED
Name: string
A non-unique identifier of the Instance.
Parent: Instance
Determines the hierarchical parent of the Instance.
NOT REPLICATED
RobloxLocked: boolean
A deprecated property that used to protect CoreGui objects.
HIDDEN
archivable: boolean
HIDDEN
NOT REPLICATED
DEPRECATED
className: string
READ ONLY
NOT REPLICATED
DEPRECATED
Methods
ClearCharacterAppearance(): void
Removes all accessories and other character appearance objects from a player's Character.
DistanceFromCharacter(point: Vector3): number
Returns the distance between the character's head and the given Vector3 point. Returns 0 if the player has no character.
GetJoinData(): table
Returns a dictionary containing information describing how the Player joins the experience.
GetMouse(): Mouse
Returns the mouse being used by the client.
GetNetworkPing(): number
Returns the isolated network latency in seconds.
HasAppearanceLoaded(): boolean
Returns whether or not the appearance of the player's character has loaded.
IsVerified(): boolean
Returns whether the player is verified with concrete, real-world signals.
Kick(message: string): void
Forcibly disconnect a player from the game, optionally providing a message.
Move(walkDirection: Vector3, relativeToCamera: boolean): void
Causes the player's character to walk in the given direction until stopped, or interrupted by the player (by using their controls).
SetAccountAge(accountAge: number): void
Sets the AccountAge of the player.
SetSuperSafeChat(value: boolean): void
Sets whether or not the player sees filtered chats, rather than normal chats.
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.
Creates a new character for the player, removing the old one. Also clears the player's Backpack and PlayerGui.
LoadCharacterWithHumanoidDescription(humanoidDescription: HumanoidDescription): void YIELDS
Spawns an avatar so it has everything equipped in the passed in HumanoidDescription.
RequestStreamAroundAsync(position: Vector3, timeOut: number): void YIELDS
Requests that the server stream to the player around the specified location.
Methods inherited from Instance
AddTag(tag: string): void
Applies a tag to the instance.
This function destroys all of an Instance's children.
Clone(): Instance
Create a copy of an object and all its descendants, ignoring objects that are not Archivable.
Sets the Instance.Parent property to nil, locks the Instance.Parent property, disconnects all connections, and calls Destroy on all children.
FindFirstAncestor(name: string): Instance
Returns the first ancestor of the Instance whose Instance.Name is equal to the given name.
FindFirstAncestorOfClass(className: string): Instance
Returns the first ancestor of the Instance whose Instance.ClassName is equal to the given className.
FindFirstAncestorWhichIsA(className: string): Instance
Returns the first ancestor of the Instance for whom Instance:IsA() returns true for the given className.
FindFirstChild(name: string, recursive: boolean): Instance
Returns the first child of the Instance found with the given name.
FindFirstChildOfClass(className: string): Instance
Returns the first child of the Instance whose ClassName is equal to the given className.
FindFirstChildWhichIsA(className: string, recursive: boolean): Instance
Returns the first child of the Instance for whom Instance:IsA() returns true for the given className.
FindFirstDescendant(name: string): Instance
Returns the first descendant found with the given Instance.Name.
GetActor(): Actor
Returns the Actor associated with the Instance, if any.
GetAttribute(attribute: string): Variant
Returns the attribute which has been assigned to the given name.
GetAttributeChangedSignal(attribute: string): RBXScriptSignal
Returns an event that fires when the given attribute changes.
GetAttributes(): table
Returns a dictionary of string → variant pairs for each of the Instance's attributes.
GetChildren(): Objects
Returns an array containing all of the Instance's children.
GetDebugId(scopeLength: number): string NOT BROWSABLE
Returns a coded string of the Instances DebugId used internally by Roblox.
GetDescendants(): Array CUSTOM LUA STATE
Returns an array containing all of the descendants of the instance.
GetFullName(): string
Returns a string describing the Instance's ancestry.
GetPropertyChangedSignal(property: string): RBXScriptSignal
Get an event that fires when a given property of an object changes.
GetTags(): Array
Gets an array of all tags applied to the instance.
Check whether the instance has a given tag.
IsA(className: string): boolean CUSTOM LUA STATE
Returns true if an Instance's class matches or inherits from a given class.
IsAncestorOf(descendant: Instance): boolean
Returns true if an Instance is an ancestor of the given descendant.
IsDescendantOf(ancestor: Instance): boolean
Returns true if an Instance is a descendant of the given ancestor.
Sets the object's Parent to nil, and does the same for all its descendants.
RemoveTag(tag: string): void
Removes a tag from the instance.
SetAttribute(attribute: string, value: Variant): void
Sets the attribute with the given name to the given value.
WaitForChild(childName: string, timeOut: number): Instance CUSTOM LUA STATE, CAN YIELD
Returns the child of the Instance with the given name. If the child does not exist, it will yield the current thread until it does.
children(): Objects DEPRECATED
Returns an array of the object's children.
clone(): Instance DEPRECATED
findFirstChild(name: string, recursive: boolean): Instance DEPRECATED
getChildren(): Objects DEPRECATED
isA(className: string): boolean DEPRECATED, CUSTOM LUA STATE
isDescendantOf(ancestor: Instance): boolean DEPRECATED
Events
CharacterAdded(character: Model): RBXScriptSignal
Fired when a player's character spawns or respawns.
CharacterAppearanceLoaded(character: Model): RBXScriptSignal
Fires when the full appearance of a Player.Character has been inserted.
CharacterRemoving(character: Model): RBXScriptSignal
Fired right before a player's character is removed.
Chatted(message: string, recipient: Player): RBXScriptSignal
Fires when a player chats in-game using Roblox's provided chat bar.
Idled(time: number): RBXScriptSignal
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.
Events inherited from Instance
AncestryChanged(child: Instance, parent: Instance): RBXScriptSignal
Fires when the Instance.Parent property of the object or one of its ancestors is changed.
AttributeChanged(attribute: string): RBXScriptSignal
Fires whenever an attribute is changed on the Instance.
Changed(property: string): RBXScriptSignal
Fired immediately after a property of an object changes.
ChildAdded(child: Instance): RBXScriptSignal
Fires after an object is parented to this Instance.
ChildRemoved(child: Instance): RBXScriptSignal
Fires after a child is removed from this Instance.
DescendantAdded(descendant: Instance): RBXScriptSignal
Fires after a descendant is added to the Instance.
DescendantRemoving(descendant: Instance): RBXScriptSignal
Fires immediately before a descendant of the Instance is removed.
Destroying(): RBXScriptSignal
Fires immediately before the instance is destroyed via Instance:Destroy().
childAdded(child: Instance): RBXScriptSignal DEPRECATED
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.
Code Samples
This code sample adds a mark to players showing about how old their account is. The mark uses a player's account age to determine if they are a New Player, Veteran Player or Regular Player.
Account Age Mark
local Players = game:GetService("Players")
local MAX_AGE_NEW_PLAYER = 7 -- one week
local MIN_AGE_VETERAN = 365 -- one year
-- This function marks a part with text using a BillboardGui
local function mark(part, text)
local bbgui = Instance.new("BillboardGui")
bbgui.AlwaysOnTop = true
bbgui.StudsOffsetWorldSpace = Vector3.new(0, 2, 0)
bbgui.Size = UDim2.new(0, 200, 0, 50)
local textLabel = Instance.new("TextLabel")
textLabel.Size = UDim2.new(1, 0, 1, 0) -- Fill parent
textLabel.Text = text
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.BackgroundTransparency = 1
textLabel.Parent = bbgui
-- Add to part
bbgui.Parent = part
bbgui.Adornee = part
end
local function onPlayerSpawned(player, character)
local head = character:WaitForChild("Head")
if player.AccountAge >= MIN_AGE_VETERAN then
mark(head, "Veteran Player")
elseif player.AccountAge <= MAX_AGE_NEW_PLAYER then
mark(head, "New Player")
else
mark(head, "Regular Player")
end
end
local function onPlayerAdded(player)
-- Listen for this player spawning
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
AutoJumpEnabled
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.Character 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.
Code Samples
This code sample is meant for a TextButton. It allows the player to toggle the auto-jumping behavior while on a mobile device.
Auto-Jump Toggle
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local button = script.Parent
local function update()
-- Update button text
if player.AutoJumpEnabled then
button.Text = "Auto-Jump is ON"
else
button.Text = "Auto-Jump is OFF"
end
-- Reflect the property in the player's character, if they have one
if player.Character then
local human = player.Character:FindFirstChild("Humanoid")
if human then
human.AutoJumpEnabled = player.AutoJumpEnabled
end
end
end
local function onActivated()
-- Toggle auto-jump
player.AutoJumpEnabled = not player.AutoJumpEnabled
-- Update everything else
update()
end
button.Activated:Connect(onActivated)
update()
CameraMaxZoomDistance
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.
Code Samples
The example demonstrates how to set a player's camera minimum and maximum zoom distance.
In this example, we set the Player.CameraMinZoomDistance and Player.CameraMaxZoomDistance to set the min and max distance in studs a player's camera can be from their character.
Note that since the example attempts to set the CameraMinZoomDistance to be greater than the CameraMaxZoomDistance, the CameraMinZoomDistance value will be decreased and set to the value of the max zoom distance.
To change the default min and max zoom distance values for a player when they first enter the game, you can change the StarterClass.Player.CameraMinZoomDistance and StarterClass.Player.CameraMaxZoomDistance properties.
Setting Camera Zoom Distance
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75
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.
Code Samples
The example demonstrates how to set a player's camera minimum and maximum zoom distance.
In this example, we set the Player.CameraMinZoomDistance and Player.CameraMaxZoomDistance to set the min and max distance in studs a player's camera can be from their character.
Note that since the example attempts to set the CameraMinZoomDistance to be greater than the CameraMaxZoomDistance, the CameraMinZoomDistance value will be decreased and set to the value of the max zoom distance.
To change the default min and max zoom distance values for a player when they first enter the game, you can change the StarterClass.Player.CameraMinZoomDistance and StarterClass.Player.CameraMaxZoomDistance properties.
Setting Camera Zoom Distance
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMaxZoomDistance = 50
player.CameraMinZoomDistance = 75
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:
First person
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.
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.
This item should be used in a LocalScript to work as expected online.
Code Samples
This example demonstrates how to change the character's CameraMode to first person using the LockFirstPerson value of the CameraMode enum.
Playing in First Person
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMode = Enum.CameraMode.LockFirstPerson
This example demonstrates how to change the character's CameraMode to third person using the Classic value of the CameraMode enum.
Playing in Third Person
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CameraMode = Enum.CameraMode.Classic
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.
Code Samples
This example demonstrates how to disable loading a player's character appearance. Instead, the player loads as a grey model without any hats, shirts, pants, etc.
This is useful for games using custom clothing and accessories.
Note that if the character has already spawned, this change will not take affect until the player respawns or the Player:LoadCharacter() function is called.
Disabling a Player's Appearance
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.CanLoadCharacterAppearance = false
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:
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character
if not character or not character.Parent then
character = player.CharacterAdded:wait()
end
CharacterAppearanceId
This property determines the user ID of the account whose character appearance is used for a player's Player.Character. By default, this property is the 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.
Code Samples
This code sample allows players to chat "/disguise xyz", where xyz is a user ID or username, and they will respawn appearing like that account's avatar. Try typing "/disguise 261" or "/disguise Shedletsky"!
Disguise Command
local Players = game:GetService("Players")
local disguiseCommand = "/disguise "
local function onPlayerChatted(player, message)
if message:sub(1, disguiseCommand:len()):lower() == disguiseCommand:lower() then
local input = message:sub(disguiseCommand:len() + 1)
local id = tonumber(input)
if not id then -- Number failed to parse, maybe they typed a username instead
pcall(function() -- This call can fail sometimes!
id = Players:GetUserIdFromNameAsync(input) -- Fetch ID from name
end)
end
if id then
-- Set character appearance then respawn
player.CharacterAppearanceId = id
player:LoadCharacter()
else
-- We couldn't get an ID from their input
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
DevCameraOcclusionMode
Defines how the default camera scripts handle objects between the camera and the camera subject. Set by StarterPlayer.DevCameraOcclusionMode and can't be changed for individual players.
The default value is Zoom (0). See DevCameraOcclusionMode for a list of available modes.
DevComputerCameraMode
The DevComputerCameraMode property determines the manner in which a player moves their camera when using a device with a mouse and keyboard. 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.
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's a good idea to allow players to choose their control mode to maximize accessibility.
It's possible to create a custom control scheme by setting this property to Scriptable.
This property doesn't affect players using a touch enabled device. See Player.DevTouchCameraMode instead.
Code Samples
The example demonstrates how to set a player's camera movement mode for players on a computer.
In this example, we set the camera movement mode to Classic via the DevComputerCameraMovementMode enum. This means that the camera of players on touch enabled devices will track the player but will not automatically rotate if the player walks left or right.
Setting a Player's Camera Movement Mode (Desktop)
local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- Set the player's camera movement mode on computers to classic
player.DevComputerCameraMode = Enum.DevComputerCameraMovementMode.Classic
DevComputerMovementMode
The DevComputerMovementMode property determines the manner in which a player moves their character when using a device with a mouse and keyboard. 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.
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's possible to create a custom control scheme by setting this property to Scriptable.
This property doesn't affect players using a touch-enabled device. See Player.DevTouchMovementMode instead.
Code Samples
The example demonstrates how to set the movement mode for players on computers.
In this example, we set the movement mode to KeyboardMouse via the DevComputerMovementMode enum. This means that players on computers can control their characters using their keyboard and mouse.
Setting a Player's Movement Mode (Desktop)
local Players = game:GetService("Players")
game.Players.PlayerAdded:Connect(function(player)
-- Set the player's movement mode on mobile devices to a dynamic thumbstick
player.DevComputerMovementMode = Enum.DevComputerMovementMode.DynamicThumbstick
end)
DevEnableMouseLock
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.
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 the 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.
Note that shift-lock related APIs are in the process of being deprecated, so it's recommended to use UserInputService.MouseBehavior instead to lock the mouse.
Code Samples
This code sample demonstrates how to toggle whether mouse lock is available to a player using a chat command. When a player types "mouselock", their ability to toggle mouse lock is toggled. Note that this does not toggle the actual state of mouse lock; rather, it changes whether a player is able to toggle it themselves.
This code can be run by pasting it into a Script within ServerScriptService.
Toggling Mouse Lock Ability
local Players = game:GetService("Players")
local function toggleMouseLock(player)
player.DevEnableMouseLock = not player.DevEnableMouseLock
if player.DevEnableMouseLock then
print("Mouse lock is available")
else
print("Mouse lock is not available")
end
end
local function onPlayerChatted(player, message, _recipient)
if message == "mouselock" then
toggleMouseLock(player)
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
DevTouchCameraMode
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.
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's possible to create a custom control scheme by setting this property to Scriptable.
This property doesn't affect players who aren't using a touch-enabled device. See Player.DevComputerCameraMovementMode instead.
Code Samples
The example demonstrates how to set a player's camera movement mode.
In this example, we set the camera movement mode to Classic via the DevTouchCameraMovementMode enum. This means that the camera of players on touch enabled devices will track the player but will not automatically rotate if the player walks left or right.
Setting a Player's Camera Movement Mode (Touch)
local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- Set the player's camera movement mode on mobile devices to classic
player.DevTouchCameraMovementMode = Enum.DevTouchCameraMovementMode.Classic
DevTouchMovementMode
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.
When set to UserChoice, a player can choose between any control mode (except Scriptable) in the Roblox game settings. In general, it's a good idea to allow players to choose their control mode to maximize accessibility.
It's possible to create a custom control scheme by setting this property to Scriptable.
This property doesn't affect players who aren't using a touch-enabled device. See Player.DevComputerMovementMode instead.
Code Samples
The example demonstrates how to set the movement mode for players on touch enabled devices.
In this example, we set the movement mode to Thumbstick via the DevTouchMovementMode enum. This means that players on touch enabled devices are able to move via a virtual thumbstick on their screen.
Setting a Player's Movement Mode (Touch)
local Players = game:GetService("Players")
game.Players.PlayerAdded:Connect(function(player)
-- Set the player's movement mode on mobile devices to a dynamic thumbstick
player.DevTouchMovementMode = Enum.DevTouchMovementMode.DynamicThumbstick
end)
DisplayName
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 Player.LoadCharacter or by the Roblox engine will have their Humanoid.DisplayName property assigned to the Player.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.
Code Samples
This code sample alerts players if a new player follows the local player into the game. It does so using a Hint. Place this in a LocalScript in StarterPlayerScripts.
Followed Alert
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local function onPlayerAdded(newPlayer)
if newPlayer.FollowUserId == player.UserId then
local hint = Instance.new("Hint")
hint.Parent = player:WaitForChild("PlayerGui")
hint.Text = "You were followed to this game by " .. newPlayer.Name .. "!"
task.delay(3, function()
if hint then
hint:Destroy()
end
end)
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
GameplayPaused
Not Accessible Security
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:
Workspace.StreamingEnabled which controls whether content streaming is enabled
Workspace.StreamingIntegrityMode and StreamingIntegrityMode for more details on when gameplay is paused.
HasVerifiedBadge
The HasVerifiedBadge Player property indicates if the player has a Verified Badge.
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.
If a Humanoid's health bar is visible, you can set the display type using Humanoid.DisplayDistanceType.
Code Samples
This example demonstrates how to hide other Humanoid's (Player and NPC) health bars and names.
This is done by setting the player's Player.HealthDisplayDistance and Player.NameDisplayDistance properties to 0.
If you would like to display health bars and names, you set the properties to a value greater than 0. For instance, setting the properties to 100 means that the player will see other player's health and names up to 100 studs away.
To modify the default values for players, you can change the values of the StarterClass.Player.HealthDisplayDistance and StarterClass.Player.NameDisplayDistance properties.
Hiding Player Health and Names
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0
LocaleId
Hidden
Read Only
Not Replicated
The LocaleId Player property shows the locale id that the local player has set for their Roblox account. It holds a string with the two letter code (for example, "en-us") for the locale.
This can be used to determine the geographic demographic of your game's player base.
This property allows access to the player's locale from the server. It is similar to LocalizationService's LocalizationService.RobloxLocaleId property.
Code Samples
This example demonstrates how to check the locale of a local player using the Player.LocaleId property. It prints a string with the two letter locale code for the locale of the local player.
For instance, if the player's local is within the US, the locale will be:
en-us
Checking a Player's Locale
local Players = game:GetService("Players")
local player = Players.LocalPlayer
print(player.LocaleId)
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 Class.CoreScripts using Player:SetMembershipType() - which are not accessible.
Code Samples
The following example checks whether a player has Premium membership.
Check Player Membership Status
local Players = game:GetService("Players")
local player = Players.LocalPlayer
if player.MembershipType == Enum.MembershipType.Premium then
-- Take some action specifically for Premium members
end
NameDisplayDistance
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.
If a Humanoid's health bar is visible, you can set the display type using Humanoid.DisplayDistanceType.
Code Samples
This example demonstrates how to hide other Humanoid's (Player and NPC) health bars and names.
This is done by setting the player's Player.HealthDisplayDistance and Player.NameDisplayDistance properties to 0.
If you would like to display health bars and names, you set the properties to a value greater than 0. For instance, setting the properties to 100 means that the player will see other player's health and names up to 100 studs away.
To modify the default values for players, you can change the values of the StarterClass.Player.HealthDisplayDistance and StarterClass.Player.NameDisplayDistance properties.
Hiding Player Health and Names
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player.HealthDisplayDistance = 0
player.NameDisplayDistance = 0
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.
Code Samples
This example checks if a player is neutral. If the player is neutral, the game prints:
Player is neutral!
If the player is neutral, the game prints:
Player is not neutral!
Note: Although this example prints the value of the local player's neutral property, you can change the example to get the value for any player.
Checking if a Player is Neutral
local Players = game:GetService("Players")
local player = Players.LocalPlayer
if player.Neutral then
print("Player is neutral!")
else
print("Player is not neutral!")
end
ReplicationFocus
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.
Code Samples
This example creates a new BasePart and sets the Player's Player.ReplicationFocus to that part.
This demonstrates the functionality of the ReplicationFocus property. You can easily change the part that the focus is set to to change the replication focus.
Setting a Player's Replication Focus
local Players = game:GetService("Players")
local PLAYER_NAME = "polarpanda16"
local player = Players:WaitForChild(PLAYER_NAME)
local part = Instance.new("Part")
part.Parent = workspace
part.Name = "ReplicationFocusPart"
part.Anchored = true
player.ReplicationFocus = part
RespawnLocation
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:
Descendant of Workspace
SpawnLocation.TeamColor is set to the Player.TeamColor or SpawnLocation.Neutral is set to true
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
A Player will spawn from SpawnLocations belonging to their team. In some cases it may be simpler to change the player's Player.Team instead.
Implement your own custom spawn logic using PVInstance:PivotTo() to manually move the Player.Character.
Code Samples
This code sample will set the player to always respawn from the last SpawnLocation they touched. New players will respawn from the SpawnLocation named 'FirstSpawn' until they touch a different SpawnLocation.
This is an alternative to using the AllowTeamChangeOnTouch property to switch SpawnLocations and does not require Teams.
Change Spawn on Touch
local Players = game:GetService("Players")
local function addSpawn(spawnLocation)
-- listen for the spawn being touched
spawnLocation.Touched:Connect(function(hit)
local character = hit:FindFirstAncestorOfClass("Model")
if character then
local player = Players:GetPlayerFromCharacter(character)
if player and player.RespawnLocation ~= spawnLocation then
local humanoid = character:FindFirstChildOfClass("Humanoid")
-- make sure the character isn't dead
if humanoid and humanoid:GetState() ~= Enum.HumanoidStateType.Dead then
print("spawn set")
player.RespawnLocation = spawnLocation
end
end
end
end)
end
local firstSpawn
-- look through the workspace for spawns
for _, descendant in pairs(workspace:GetDescendants()) do
if descendant:IsA("SpawnLocation") then
if descendant.Name == "FirstSpawn" then
firstSpawn = descendant
end
addSpawn(descendant)
end
end
local function playerAdded(player)
player.RespawnLocation = firstSpawn
end
-- listen for new players
Players.PlayerAdded:Connect(playerAdded)
-- go through existing players
for _, player in pairs(Players:GetPlayers()) do
playerAdded(player)
end
Team
Not Replicated
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.
Code Samples
This code sample, although lengthy, is quite simple: detect when a player chats /play, then put them on the "Playing" team. When they die, move them back to the "Spectating" team.
Playing/Spectating Teams
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
local teamPlaying = Teams.Playing
local teamSpectators = Teams.Spectating
local playCommand = "/play"
local function play(player)
player.Team = teamPlaying
player.TeamColor = teamPlaying.TeamColor
-- Respawn the player (moves them to spawn location)
player:LoadCharacter()
end
local function onPlayerDied(player, _character)
-- When someone dies, put them on the spectator team
player.Team = teamSpectators
end
local function onPlayerSpawned(player, character)
local human = character:WaitForChild("Humanoid")
human.Died:Connect(function()
onPlayerDied(player, character)
end)
end
local function onPlayerChatted(player, message)
if message:sub(1, playCommand:len()):lower() == playCommand then
play(player)
end
end
local function onPlayerAdded(player)
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
player.Chatted:Connect(function(message, _recipient)
onPlayerChatted(player, message)
end)
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
This code sample allows any player to chat "/jointeam " where is the name of a team. It uses string manipulation using string.sub and string.lower to make the command case-insensitive and allow for partial matches. For example, "/jointeam red" will match the team "Red Robins".
Join Team Command
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
-- Command to choose a team (note the trailing space)
local joinCommand = "/jointeam "
local function findTeamByName(name)
-- First, check for the exact name of a team
if Teams:FindFirstChild(name) then
return Teams[name]
end
-- Let's check for case-insensitive partial matches, like "red" for "Red Robins"
for _, team in pairs(Teams:GetChildren()) do
if team.Name:sub(1, name:len()):lower() == name:lower() then
return team
end
end
-- If we get to this point, no team matched the one we were looking for :(
end
local function onPlayerChatted(player, message, _recipient)
-- Note: string.sub(message, ...) is the same as message:sub(...)
if message:sub(1, joinCommand:len()):lower() == joinCommand:lower() then
-- Matched "/JOINTEAM xyz" to our join command prefix "/jointeam "
local teamName = message:sub(joinCommand:len() + 1) -- Cut out the "xyz" from "/jointeam xyz"
local team = findTeamByName(teamName)
if team then
-- Set the team!
player.Team = team
player.Neutral = false
else
-- Tell the player that team could not be found :(
player.Team = nil
player.Neutral = true
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
TeamColor
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 team across many scripts; this is something you want to avoid when adhering to the don't-repeat-yourself principle.
Code Samples
This code sample, although lengthy, is quite simple: detect when a player chats /play, then put them on the "Playing" team. When they die, move them back to the "Spectating" team.
Playing/Spectating Teams
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
local teamPlaying = Teams.Playing
local teamSpectators = Teams.Spectating
local playCommand = "/play"
local function play(player)
player.Team = teamPlaying
player.TeamColor = teamPlaying.TeamColor
-- Respawn the player (moves them to spawn location)
player:LoadCharacter()
end
local function onPlayerDied(player, _character)
-- When someone dies, put them on the spectator team
player.Team = teamSpectators
end
local function onPlayerSpawned(player, character)
local human = character:WaitForChild("Humanoid")
human.Died:Connect(function()
onPlayerDied(player, character)
end)
end
local function onPlayerChatted(player, message)
if message:sub(1, playCommand:len()):lower() == playCommand then
play(player)
end
end
local function onPlayerAdded(player)
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
player.Chatted:Connect(function(message, _recipient)
onPlayerChatted(player, message)
end)
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
UserId
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.
Code Samples
The below example would print the UserId of every user who entered a game.
Player.UserId
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print(player.UserId)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Players:GetPlayerByUserId
local Players = game:GetService("Players")
local player = Players:GetPlayerByUserId(1)
if player then
print("Player with userId 1 is in this server! Their name is: " .. player.Name)
else
print("Player with userId 1 is not in this server!")
end
The following code sample gives an example of a 'met the creator' badge system. This script will award a specified badge (BADGE_ID) to anyone who is in a server at the same time as the user associated with OWNER_ID.
Met the Creator Badge
local BadgeService = game:GetService("BadgeService")
local Players = game:GetService("Players")
local OWNER_ID = 212423 -- can use game.CreatorId for published places
local BADGE_ID = 1
local ownerInGame = false
local function playerAdded(newPlayer)
if newPlayer.UserId == OWNER_ID then
-- if new player is the owner, set ownerInGame to true and give everyone the badge
ownerInGame = true
for _, player in pairs(Players:GetPlayers()) do
-- don't award the owner
if player ~= newPlayer then
BadgeService:AwardBadge(player.UserId, BADGE_ID)
end
end
elseif ownerInGame then
-- if the owner is in the game, award the badge
BadgeService:AwardBadge(newPlayer.UserId, BADGE_ID)
end
end
local function playerRemoving(oldPlayer)
if oldPlayer.UserId == OWNER_ID then
ownerInGame = false
end
end
Players.PlayerAdded:Connect(playerAdded)
Players.PlayerRemoving:Connect(playerRemoving)
This code sample retrieves a player's saved gold from a data store and puts the returned value onto the leaderboard. Note that this sample does not save players' gold — it only loads it.
Data Store to Leaderboard
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local goldDataStore = DataStoreService:GetDataStore("Gold")
local STARTING_GOLD = 100
local function onPlayerAdded(player)
local playerKey = "Player_" .. player.UserId
local leaderstats = Instance.new("IntValue")
leaderstats.Name = "leaderstats"
local gold = Instance.new("IntValue")
gold.Name = "Gold"
gold.Parent = leaderstats
local success, result = pcall(function()
return goldDataStore:GetAsync(playerKey) or STARTING_GOLD
end)
if success then
gold.Value = result
else
-- Failed to retrieve data
warn(result)
end
leaderstats.Parent = player
end
Players.PlayerAdded:Connect(onPlayerAdded)
Properties inherited from Instance
Archivable
This property determines whether an object should be included when the game is published or saved, or when Instance:Clone() is called on one of the object's ancestors. Calling Clone directly on an object will return nil if the cloned object is not archivable. Copying an object in Studio (using the 'Duplicate' or 'Copy' options) will ignore the Archivable property and set Archivable to true for the copy.
local part = Instance.new("Part")
print(part:Clone()) --> Part
part.Archivable = false
print(part:Clone()) --> nil
ClassName
Read Only
Not Replicated
A read-only string representing the class this Instance belongs to.
This property can be used with various other functions of Instance that are used to identify objects by type, such as Instance:IsA() or Instance:FindFirstChildOfClass().
Note this property is read only and cannot be altered by scripts. Developers wishing to change an Instance's class will instead have to create a new Instance.
Unlike Instance:IsA(), ClassName can be used to check if an object belongs to a specific class ignoring class inheritance. For example:
for _, child in ipairs(game.Workspace:GetChildren()) do
if child.ClassName == "Part" then
print("Found a Part")
-- will find Parts in model, but NOT TrussParts, WedgeParts, etc
end
end
Name
A non-unique identifier of the Instance.
This property is an identifier that describes an object. Names are not necessarily unique identifiers however; multiple children of an object may share the same name. Names are used to keep the object hierarchy organized, along with allowing scripts to access specific objects.
The name of an object is often used to access the object through the data model hierarchy using the following methods:
local baseplate = workspace.Baseplate
local baseplate = workspace["Baseplate"]
local baseplate = workspace:FindFirstChild("BasePlate")
In order to make an object accessible using the dot operator, an object's Name must follow a certain syntax. The objects name must start with an underscore or letter. The rest of the name can only contain letters, numbers, or underscores (no other special characters). If an objects name does not follow this syntax it will not be accessible using the dot operator and Lua will not interpret its name as an identifier.
If more than one object with the same name are siblings then any attempt to index an object by that name will return the only one of the objects found similar to Instance:FindFirstChild(), but not always the desired object. If a specific object needs to be accessed through code, it is recommended to give it a unique name, or guarantee that none of its siblings share the same name as it.
Note, a full name showing the instance's hierarchy can be obtained using Instance:GetFullName().
Parent
Not Replicated
The Parent property determines the hierarchical parent of the Instance. The following terminology is commonly used when talking about how this property is set:
An object is a child (parented to) another object when its Parent is set to that object.
The descendants of an Instance are the children of that object, plus the descendants of the children as well.
The ancestors of an Instance are all the objects that the Instance is a descendant of.
It is from this property that many other API members get their name, such as GetChildren and FindFirstChild.
The Remove function sets this property to nil. Calling Destroy will set the Parent of an Instance and all of its descendants to nil, and also lock the Parent property. An error is raised when setting the Parent of a destroyed object.
This property is also used to manage whether an object exists in the game or needs removed. As long as an objects parent is in the DataModel, is stored in a variable, or is referenced by another objects property, then the object remains in the game. Otherwise, the object will automatically be removed. The top level DataModel object (the one referred to as the game by scripts) has no parent, but always has a reference held to it by the game engine, and exists for the duration of a session.
Newly created objects using Instance.new() will not have a parent, and usually will not be visible or function until one is set. The most elementary creation of an object has two steps: creating the object, then setting its parent.
-- Create a part and parent it to the workspace
local part = Instance.new("Part")
part.Parent = workspace
-- Instance new can also take Parent as a second parameter
Instance.new("NumberValue", workspace)
Object Replication
An object created by server will not replicate to clients until it is parented to some object that is replicated. When creating an object then setting many properties, it's recommended to set Parent last. This ensures the object replicates once, instead of replicating many property changes.
local part = Instance.new("Part") -- Avoid using the second parameter here
part.Anchored = true
part.BrickColor = BrickColor.new("Really red")
-- Potentially many other property changes could go here here...
-- Always set parent last!
part.Parent = workspace
However, if you were parenting your parts to a Model whose parent hasn't been set yet, then setting the parent first would not matter as the model would not have replicated yet.
RobloxLocked
Hidden
Plugin Security
This property used to protect objects in the CoreGui service from being altered by users in an unauthorized manner. It has been deprecated and does not do anything.
archivable
Hidden
Not Replicated
DEPRECATED
DEPRECATED
This deprecated property is a variant of Instance.Archivable which should be used instead.
className
Read Only
Not Replicated
DEPRECATED
DEPRECATED
This deprecated property is a variant of Instance.ClassName which should be used instead.
Methods
ClearCharacterAppearance
void
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.
It does not remove t-shirts, head meshes, or faces.
Returns
void
Code Samples
How to Clear a Character's Appearance
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local function onChildRemoved(child)
print(child.ClassName, "removed from character")
end
character.ChildRemoved:Connect(onChildRemoved)
player:ClearCharacterAppearance()
--> BodyColors removed from character
--> ShirtGraphic removed from character
--> Shirt removed from character
--> Pants removed from character
--> CharacterMesh removed from character
--> Hat removed from character
--> Shirt removed from character
DistanceFromCharacter
The DistanceFromCharacter Player function returns the 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.
If you would like to determine the distance between two non-player instances or positions, you can use the following:
local distance = (position1 - position2).magnitude
Parameters
point: Vector3
The location from which player's distance to is being measured.
Returns
The distance in studs between the player and the location.
Code Samples
This example demonstrates how to measure the distance between a player's Player.Character and another location.
This code will print the distance of each player's character from the origin (0, 0, 0):
Measuring the Distance Between a Player and a Position
local Players = game:GetService("Players")
for _, player in pairs(Players:GetPlayers()) do
print(player:DistanceFromCharacter(Vector3.new(0, 0, 0)))
end
GetJoinData
Returns a dictionary containing information describing how the 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 Player.UserId numbers of the users teleported alongside the Player. Only present if the player teleported as part of a group.
TeleportData
variant
Reflects the teleportData specified in the original teleport. Useful for sharing information between servers the player teleports to. Only present if teleportData was specified and a server calls the teleport function.
LaunchData
string
A string containing launch data specified in the URL the player clicks to join the experience. Only present if the URL contains launch data.
GetJoinData and TeleportData
If a server initiates the Player's teleport, the dictionary that 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
The following example tracks sources of traffic for analytics. By creating URLs with unique launch data for each social platform, you can determine the most popular traffic sources. The sample checks the source against a list of possible samples and discards any invalid sources because users can modify the launch data.
Tracking Traffic Sources
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local analyticsStore = DataStoreService:GetDataStore("Analytics")
local ALLOWED_SOURCES = {
"twitter";
"youtube";
"discord";
}
local function onPlayerAdded(player)
local source = player:GetJoinData().LaunchData
-- check if the provided source is valid
if source and table.find(ALLOWED_SOURCES, source) then
-- update the data store to track the source popularity
local success, result = pcall(analyticsStore.IncrementAsync, analyticsStore, source)
if success then
print(player.Name, "joined from", source, "- total:", result)
else
warn("Failed to record join source: " .. result)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
The following example generates a URL with the user's ID used as launch data. It then displays the URL in a read-only text box that makes it easy for the user to copy and share the link with their friends. When a user joins the game using a referral link, you can use the launch data to reward the referrer.
Referral URL Generator
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local DIRECT_JOIN_URL = "https://www.roblox.com/games/start?placeId=%d&launchData=%s"
local textBox = script.Parent
local function generateReferralURL(player)
return DIRECT_JOIN_URL:format(
game.PlaceId,
player.UserId
)
end
local function highlightAll()
if -- avoid recursive property updates
textBox:IsFocused()
and not (
textBox.SelectionStart == 1
and textBox.CursorPosition == #textBox.Text + 1
)
then
textBox.SelectionStart = 1
textBox.CursorPosition = #textBox.Text + 1
end
end
textBox.Focused:Connect(highlightAll)
textBox:GetPropertyChangedSignal("SelectionStart"):Connect(highlightAll)
textBox:GetPropertyChangedSignal("CursorPosition"):Connect(highlightAll)
textBox.TextEditable = false
textBox.ClearTextOnFocus = false
textBox.Text = generateReferralURL(player)
The following example is a function that converts a table into a string you can use as launch data. The provided data is JSON encoded, checked for valid character length, and escaped with percent signs.
Using a Table as Launch Data
local HttpService = game:GetService("HttpService")
local DATA_CHARACTER_LIMIT = 200
local function encodeTableAsLaunchData(data)
-- convert the table to a string
local jsonEncodedData = HttpService:JSONEncode(data)
if #jsonEncodedData <= DATA_CHARACTER_LIMIT then
-- escape potentially invalid characters, such as spaces
local urlEncodedData = HttpService:UrlEncode(jsonEncodedData)
return true, urlEncodedData
else
-- report character limit error
return false, ("Encoded table exceeds %d character limit"):format(DATA_CHARACTER_LIMIT)
end
end
local sampleData = {
joinMessage = "Hello!";
urlCreationDate = os.time();
magicNumbers = {
534;
1337;
746733573;
};
}
local success, encodedData = encodeTableAsLaunchData(sampleData)
if success then
print(encodedData)
else
warn("failed to encode launch data: " .. encodedData)
end
The following example attempts to decode launch data, using pcall to prevent an error in case the data is corrupt.
Decoding JSON Launch Data
local HttpService = game:GetService("HttpService")
local Players = game:GetService("Players")
local function onPlayerAdded(player)
local launchData = player:GetJoinData().LaunchData
if launchData then
-- attempt to decode the data
local success, result = pcall(HttpService.JSONDecode, HttpService, launchData)
if success then
print(player.Name, "joined with data:", result)
else
-- this is probably due to the user messing with the URL
warn("Failed to parse launch data:" .. result)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
The following code sample is an example of how teleport data can be retrieved on the server using Player:GetJoinData(). This code, when ran in a Script in ServerScriptService, will listen for new Player|Players joining the game. When they join it will retrieve their teleport data (verifying it came from a valid place) to find their current level.
Server TeleportData Example
local Players = game:GetService("Players")
local approvedPlaceIds = { 1 } -- insert approved PlaceIds here
local function isPlaceIdApproved(placeId)
for _, id in pairs(approvedPlaceIds) do
if id == placeId then
return true
end
end
return false
end
local function onPlayerAdded(player)
local joinData = player:GetJoinData()
-- verify this data was sent by an approved place
if isPlaceIdApproved(joinData.SourcePlaceId) then
local teleportData = joinData.TeleportData
if teleportData then
local currentLevel = teleportData.currentLevel
print(player.Name .. " is on level " .. currentLevel)
end
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
GetMouse
The GetMouse Player function returns the Mouse being 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
The below example will print:
Button 1 is down
whenever the Players.LocalPlayer left clicks.
How to Track Mouse Input
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
local function onButton1Down()
print("Button 1 is down")
end
mouse.Button1Down:Connect(onButton1Down)
GetNetworkPing
GetNetworkPing returns the isolated network latency 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. It doesn't involve data deserialization or processing.
For client-side LocalScripts, this function can only be called on the Players.LocalPlayer. This function is useful in identifying and debugging issues that occur in high network latency scenarios. It's also useful for masking latency, such as adjusting the speed of throwing animations for projectiles.
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
This example prints the result of Player:HasAppearanceLoaded() after a player joins the game until the player's appearance has loaded.
Check if a Player's Appearance Has Loaded
local Players = game:GetService("Players")
local function onPlayerAdded(player)
local loaded = player:HasAppearanceLoaded()
print(loaded)
while not loaded do
loaded = player:HasAppearanceLoaded()
print(loaded)
task.wait()
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
IsVerified
Returns a boolean value indicating that player's verification status. When true, the player is verified. Verification includes, but isn't limited to, non-VOIP phone number or government ID verification.
When implementing IsVerified, exercise caution to ensure that the implementation does not inadvertently block all unverified users.
Note that the method can only be called on the backend server. Calling it client-side results in an error. Additionally, this method will always return false in Studio.
Returns
A boolean indicating whether the player is verified.
Code Samples
The following example prints "true" if the player is verified.
Using IsVerified
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print(player:IsVerified())
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Kick
void
The Kick() method allows an experience to gracefully disconnect a client and optionally provide a message to the disconnected user. This is useful for moderating abusive users. You should only allow specific users whom you trust to trigger this method on other users.
Calling this method on a Player with no arguments disconnects the user from the server and provides a default notice message. Calling this method on a Player along with a string as the first argument replaces the default message with the provided string.
When using this method from a LocalScript, only the local user's client can be kicked.
Parameters
message: string
The message to show the user upon kicking.
Default Value: ""
Returns
void
Move
void
The Move Player function causes the player's character to walk 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
void
Code Samples
The following example would cause the LocalPlayer to walk forward, towards where their camera is pointing.
Moving the Player Towards Their Camera
game.Players.LocalPlayer:Move(Vector3.new(0, 0, -1), true)
SetAccountAge
void
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
void
Code Samples
This example demonstrates how the Player:SetAccountAge() function would be used if it was accessible. It sets the local player's account age to 100 days.
Setting the Player's Account Age
local Players = game:GetService("Players")
local player = Players.LocalPlayer
player:SetAccountAge(100)
This code sample adds a mark to players showing about how old their account is. The mark uses a player's account age to determine if they are a New Player, Veteran Player or Regular Player.
Account Age Mark
local Players = game:GetService("Players")
local MAX_AGE_NEW_PLAYER = 7 -- one week
local MIN_AGE_VETERAN = 365 -- one year
-- This function marks a part with text using a BillboardGui
local function mark(part, text)
local bbgui = Instance.new("BillboardGui")
bbgui.AlwaysOnTop = true
bbgui.StudsOffsetWorldSpace = Vector3.new(0, 2, 0)
bbgui.Size = UDim2.new(0, 200, 0, 50)
local textLabel = Instance.new("TextLabel")
textLabel.Size = UDim2.new(1, 0, 1, 0) -- Fill parent
textLabel.Text = text
textLabel.TextColor3 = Color3.new(1, 1, 1)
textLabel.TextStrokeTransparency = 0
textLabel.BackgroundTransparency = 1
textLabel.Parent = bbgui
-- Add to part
bbgui.Parent = part
bbgui.Adornee = part
end
local function onPlayerSpawned(player, character)
local head = character:WaitForChild("Head")
if player.AccountAge >= MIN_AGE_VETERAN then
mark(head, "Veteran Player")
elseif player.AccountAge <= MAX_AGE_NEW_PLAYER then
mark(head, "New Player")
else
mark(head, "Regular Player")
end
end
local function onPlayerAdded(player)
-- Listen for this player spawning
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
SetSuperSafeChat
void
Plugin Security
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 players cannot see unfiltered messages.
For example, entering the following command in the command prompt would enable SuperSafeChat for the player named polarpanda16, as long as that player is in the game:
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
void
GetFriendsOnline
Yields
This function returns a dictionary array of online friends, limited by the maxFriends value. The function uses a 30 second cache.
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).
Name
Type
Description
VisitorId
number
The Player.UserId of the friend.
UserName
string
The username of the friend.
DisplayName
string
The Player.DisplayName of the friend.
LastOnline
string
When the friend was last online.
IsOnline
boolean
If the friend is currently online.
LastLocation
string
The name of the friend's current location.
PlaceId
number
The place ID of the friend's last location.
GameId
string
The DataModel/JobId of the friend's last location.
LocationType
number
The location type of the friend's last location:
0
Mobile Website
1
Mobile InGame
2
Webpage
3
Studio
4
InGame
5
Xbox
6
Team 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
This example demonstrates how to get a dictionary of a player's online friends. It returns the maximum number of friends specified by the argument, or 200 if an argument is not provided.
Get a List of Online Friends
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local success, result = pcall(player.GetFriendsOnline, player, 10)
if success then
for _, friend in pairs(result) do
print(friend.UserName)
end
else
warn("Failed to get online players: " .. result)
end
GetRankInGroup
Yields
The GetRankInGroup Player function returns the player's rank in the group as an integer between 0 and 255, where 0 is a non-member and 255 is the group's owner.
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
The code below will check if a player that has entered the game has a rank equal to 255, in a group with an ID of 2. If they are, it will print "Player is the owner of the group, 'LOL'!", otherwise "Player is NOT the owner of the group, 'LOL'!" will be printed to the output.
How to Check a Player's Rank in a Group
local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:GetRankInGroup(2) == 255 then
print("Player is the owner of the group, 'LOL'!")
else
print("Player is NOT the owner of the group, 'LOL'!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
GetRoleInGroup
Yields
The GetRoleInGroup Player function returns the player's role in the group as a string, or Guest if the player isn't part of the group.
Using this in a Script, as opposed to a LocalScript, 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
The code below will print the name of the rank that the player is currently a part of, in a specific group. In this instance we're checking what rank the player is within a group which has a group ID of 2.
How to Check a Player's Role in a Group
local Players = game:GetService("Players")
local function onPlayerAdded(player)
print("Player is ranked as '", player:GetRoleInGroup(2), "' in group, 'LOL'!")
end
Players.PlayerAdded:Connect(onPlayerAdded)
IsFriendsWith
Yields
This function sends a request to the Roblox website asking whether 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 Player.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
The below example would print whether or not a recently added player is friends with Gordonrox24.
How to Check if a Player is a Friend
local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:IsFriendsWith(146569) then
print(player.Name .. " is friends with gordonrox24!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
IsInGroup
Yields
The IsInGroup Player function sends a request to the Roblox website asking whether a player is a member of a group, given the ID of that group.
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
The below example will print "Player is in the Roblox Fan club!" if the newly added player is in the group with a groupId of 7.
How to Check if a Player is in a Group
local Players = game:GetService("Players")
local function onPlayerAdded(player)
if player:IsInGroup(7) then
print("Player is in the Roblox Fan club!")
end
end
Players.PlayerAdded:Connect(onPlayerAdded)
LoadCharacter
void
Yields
The LoadCharacter Player function creates a new character for 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 a 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):
Player.Character sets
Player.CharacterAdded fires
Player.Changed fires with a value of "Character"
Character appearance initializes
Player.CharacterAppearanceLoaded fires
Character.Parent sets to the DataModel
The Character rig builds, and the Character scales
Character moves to the spawn location
LoadCharacter returns
Returns
void
Code Samples
This script turns off auto-loading and simulates character respawning.
Turn Off Auto-Loading and Simulate Character Respawn
local Players = game:GetService("Players")
local RESPAWN_DELAY = 5
Players.CharacterAutoLoads = false
local function onPlayerAdded(player)
local function onCharacterAdded(character)
local humanoid = character:WaitForChild("Humanoid")
local function onDied()
task.wait(RESPAWN_DELAY)
player:LoadCharacter()
end
humanoid.Died:Connect(onDied)
end
player.CharacterAdded:Connect(onCharacterAdded)
player:LoadCharacter()
end
Players.PlayerAdded:Connect(onPlayerAdded)
LoadCharacterWithHumanoidDescription
void
Yields
This function spawns an avatar so it has everything equipped in the 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
void
Code Samples
To create a HumanoidDescription and then spawn a character with that description applied, add a Script (not a LocalScript) to the workspace and add this code to it.
Spawn Characters With HumanoidDescription
local Players = game:GetService("Players")
Players.CharacterAutoLoads = false
local function onPlayerAdded(player)
local humanoidDescription = Instance.new("HumanoidDescription")
humanoidDescription.HatAccessory = "2551510151,2535600138"
humanoidDescription.BodyTypeScale = 0.1
humanoidDescription.ClimbAnimation = 619521311
humanoidDescription.Face = 86487700
humanoidDescription.GraphicTShirt = 1711661
humanoidDescription.HeadColor = Color3.new(0, 1, 0)
player:LoadCharacterWithHumanoidDescription(humanoidDescription)
end
Players.PlayerAdded:Connect(onPlayerAdded)
RequestStreamAroundAsync
void
Yields
For experiences where instance streaming is enabled, requests that the server stream to the player regions (parts and terrain) around the specified X, Y, Z location in the 3D world. It is useful if the experience 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
void
Methods inherited from Instance
AddTag
void
This method applies a tag to the instance, with no effect if the tag is already applied. Successfully adding a tag will fire a signal created by CollectionService:GetInstanceAddedSignal() with the given tag.
Note that when tagging an instance, it's common that some resources are used to give the tag its functionality, for example event connections or tables. To prevent memory leaks, it's a good idea to clean these up (disconnect, set to nil, etc.) when no longer needed for a tag. Do this when calling Instance:RemoveTag(), calling Instance:Destroy(), or in a function connected to a signal returned by CollectionService:GetInstanceRemovedSignal().
Parameters
tag: string
Returns
void
ClearAllChildren
void
This function destroys all of an Instance's children.
As Instance:Destroy() also calls itself on the children of an object it is used on, this function will destroy all descendants.
Alternatives to ClearAllChildren
If the developer does not wish to destroy all descendants, they should use Instance:GetChildren() or Instance:GetDescendants() to loop through an object and select what to destroy. For example, the following code sample will destroy all parts in an object.
for _, instance in pairs(object:GetDescendants()) do
if instance:IsA("BasePart") then
instance:Destroy()
end
end
Returns
void
Code Samples
This example creates a Part and adds a few sparkle objects to the part. Then it calls Part:ClearAllChildren() to remove all of the children.
Instance:ClearAllChildren
local part = Instance.new("Part")
-- add some sparkles
for _ = 1, 3 do
local sparkles = Instance.new("Sparkles")
sparkles.Parent = part
end
print("Part has", #part:GetChildren(), "children")
--> Part has 3 children
part:ClearAllChildren()
print("Part has", #part:GetChildren(), "children")
--> Part has 0 children
Clone
Clone creates a copy of an object and all of its descendants, ignoring all objects that are not Archivable. The copy of the root object is returned by this function and its Parent is set to nil.
If a reference property such as ObjectValue.Value is set in a cloned object, the value of the copy's property depends on original's value:
If a reference property refers to an object that was also cloned, an internal reference, the copy will refer to the copy.
If a reference property refers to an object that was not cloned, an external reference, the same value is maintained in the copy.
This function is typically used to create models that can be regenerated. First, get a reference to the original object. Then, make a copy of the object and insert the copy by setting its Parent to the Workspace or one of its descendants. Finally, when it's time to regenerate the model, Destroy the copy and clone a new one from the original like before.
Returns
Code Samples
This code first references an existing object in the original variable. Then, it makes a copy of the object, sets the parent to that of the original, and finally moves the copy to (0, 50, 0).
Clone Example
-- Get a reference to an existing object
local original = workspace.Model
-- Create the model copy
local copy = original:Clone()
-- Parent the copy to the same parent as the original
copy.Parent = original.Parent
-- Move the copy so it's not overlapping the original
copy:SetPrimaryPartCFrame(CFrame.new(0, 50, 0))
Destroy
void
Sets the Instance.Parent property to nil, locks the Instance.Parent property, disconnects all connections, and calls Destroy on all children. This function is the correct way to dispose of objects that are no longer required. Disposing of unneeded objects is important, since unnecessary objects and connections in a place use up memory (this is called a memory leak) which can lead to serious performance issues over time.
Tip: After calling Destroy on an object, set any variables referencing the object (or its descendants) to nil. This prevents your code from accessing anything to do with the object.
local part = Instance.new("Part")
part.Name = "Hello, world"
part:Destroy()
-- Don't do this:
print(part.Name) --> "Hello, world"
-- Do this to prevent the above line from working:
part = nil
Once an Instance has been destroyed by this method it cannot be reused because the Instance.Parent property is locked. To temporarily remove an object, set Parent it to nil instead. For example:
object.Parent = nil
wait(2)
object.Parent = workspace
To Destroy an object after a set amount of time, use Debris:AddItem().
Returns
void
Code Samples
Instance:Destroy
local Part = workspace.Part
Part:Destroy()
Part.Parent = workspace --> The Parent property of Part is locked
FindFirstAncestor
Returns the first ancestor of the Instance whose Instance.Name is equal to the given name.
This function works upwards, meaning it starts at the Instance's immediate Instance.Parent and works up towards the DataModel. If no matching ancestor is found, it returns nil.
The following code snippet would find the first ancestor of the object named 'Car'.
local car = object:FindFirstAncestor("Car")
For variants of this function that find ancestors of a specific class, please see Instance:FindFirstAncestorOfClass() and Instance:FindFirstAncestorWhichIsA().
Parameters
name: string
The Instance.Name to be looked for.
Returns
The Instance found.
FindFirstAncestorOfClass
Returns the first ancestor of the Instance whose Instance.ClassName is equal to the given className.
This function works upwards, meaning it starts at the Instance's immediate Instance.Parent and works up towards the DataModel. If no matching ancestor is found, it returns nil.
A common use of this function is finding the Model a BasePart belongs to. For example:
local model = part:FindFirstAncestorOfClass("Model")
This function is a variant of Instance:FindFirstAncestor() which checks the Instance.ClassName property rather than Instance.Name. Instance:FindFirstAncestorWhichIsA() also exists, using the Instance:IsA() method instead to respect class inheritance.
Parameters
className: string
The Instance.ClassName to be looked for.
Returns
The Instance found.
FindFirstAncestorWhichIsA
Returns the first ancestor of the Instance for whom Instance:IsA() returns true for the given className.
This function works upwards, meaning it starts at the Instance's immediate Instance.Parent and works up towards the DataModel. If no matching ancestor is found, it returns nil.
Unlike Instance:FindFirstAncestorOfClass(), this function uses Instance:IsA() which respects class inheritance. For example:
print(part:IsA("Part")) --> true
print(part:IsA("BasePart")) --> true
print(part:IsA("Instance")) --> true
Therefore, the following code sample will return the first BasePart ancestor, regardless of if it is a WedgePart, MeshPart or Part.
local part = object:FindFirstAncestorWhichIsA("BasePart")
See also, Instance:FindFirstAncestor().
Parameters
className: string
The Instance.ClassName to be looked for.
Returns
The Instance found.
FindFirstChild
Returns the first child of the Instance with the given name,
or nil if no such child exists. If the optional recursive argument is true, this function searches all descendants rather than only the immediate children of the Instance.
Checking the Existence of an Object
FindFirstChild is necessary if you need to verify an object exists before continuing. Attempting to index a child by name using the dot operator throws an error if the child doesn't exist.
-- The following line errors if Part doesn't exist in the Workspace:
workspace.Part.Transparency = 0.5
Use FindFirstChild to first check for Part, then use an if-statement to run code that needs it.
local part = workspace:FindFirstChild("Part")
if part then
part.Transparency = 0.5
end
Finding a Child Whose Name Matches a Property
Sometimes the Name of an object is the same as that of a property of its Parent. When using the dot operator, properties take precedence over children if they share a name.
In the following example, a Folder called "Color" is added to a Part, which also has the Part.Color property. Part.Color refers to the Color3, not the Folder.
local part = Instance.new("Part")
local folder = Instance.new("Folder")
folder.Name = "Color"
folder.Parent = part
local c = part.Color --> A Color3
local c2 = part:FindFirstChild("Color") --> The Folder
A benefit of using FindFirstChild() in this way is that the introduction of new properties does not impose a risk on your code.
Performance Note
FindFirstChild() takes about 20% longer than using the dot operator and almost 8 times longer than simply storing a reference to an object. Therefore, you should avoid calling it in performance-dependent code such as in tight loops or functions connected to RunService.Heartbeat and RunService.RenderStepped. Instead, store the result in a variable, or consider using ChildAdded or WaitForChild() to detect when a child of a given name becomes available.
Parameters
name: string
The Instance.Name to be searched for.
recursive: boolean
Whether or not the search should be conducted recursively.
Default Value: false
Returns
The Instance found.
Code Samples
The below would look in Workspace for an object name "Brick". If found, it will change the name of the object to "Foo".
Instance:FindFirstChild
local found = workspace:FindFirstChild("Brick")
if found then
found.Name = "Foo"
end
FindFirstChildOfClass
Returns the first child of the Instance whose ClassName is equal to the given className.
If no matching child is found, this function returns nil.
Unlike Instance:FindFirstChildWhichIsA() this function uses only returns objects whose class matches the given className, ignoring class inheritance.
Developers looking for a child by name should use Instance:FindFirstChild() instead.
Parameters
className: string
The Instance.ClassName to be looked for.
Returns
The Instance found.
Code Samples
Instance:FindFirstChildOfClass
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid
while not humanoid do
humanoid = character:FindFirstChildOfClass("Humanoid")
if not humanoid then
character.ChildAdded:Wait()
end
end
FindFirstChildWhichIsA
Returns the first child of the Instance for whom Instance:IsA() returns true for the given className.
If no matching child is found, this function returns nil. If the optional recursive argument is true, this function searches all descendants rather than only the immediate children of the Instance.
Unlike Instance:FindFirstChildOfClass(), this function uses Instance:IsA() which respects class inheritance. For example:
print(part:IsA("Part")) --> true
print(part:IsA("BasePart")) --> true
print(part:IsA("Instance")) --> true
Therefore, the following code sample will return the first BasePart child, regardless of if it is a WedgePart, MeshPart or Part.
local part = object:FindFirstChildWhichIsA("BasePart")
Developers looking for a child by name, should use Instance:FindFirstChild() instead.
Parameters
className: string
The Instance.ClassName to be searched for.
recursive: boolean
Whether or not the search should be conducted recursively.
Default Value: false
Returns
The Instance found.
FindFirstDescendant
Returns the first descendant found with the given Instance.Name.
Parameters
name: string
The Instance.Name to search for.
Returns
The Instance found.
GetActor
If the Instance is an Actor, the Actor itself is returned. Otherwise, its closest ancestor Actor is returned. If no ancestor is an Actor, the result is nil.
Returns
The Actor found.
GetAttribute
Variant
This function returns the attribute which has been assigned to the given name. If no attribute has been assigned then nil is returned.
For example, the following code snippet will set the value of the instance's InitialPostion attribute. Note that this code sample does not define Instance:
local initialPosition = instance:GetAttribute("InitialPosition")
See also:
Instance:SetAttribute(), sets the attribute with the given name to the given value
Instance:GetAttributes(), returns a dictionary of string → variant pairs for each of the instance's attributes
Instance.AttributeChanged, fires whenever an attribute is changed on the instance
Instance:GetAttributeChangedSignal(), returns an event that fires when the given attribute changes
Parameters
attribute: string
The name of the attribute being retrieved.
Returns
Variant
The attribute which has been assigned to the given name. If no attribute has been assigned then nil is returned.
GetAttributeChangedSignal
This function returns an event that behaves exactly like the Changed event, except that the event only fires when the given attribute changes. It's generally a good idea to use this method instead of a connection to Changed with a function that checks the attribute name. Subsequent calls to this method on the same object with the same attribute name return the same event.
It is similar to Instance:GetPropertyChangedSignal() but for attributes.
For example, the following code snippet will return a signal that fires the function Instance.AttributeChanged when the instance's InitialPosition attribute changes. Note that this code sample does not define Instance:
local function attributeChanged()
print("Attribute changed")
end
instance:GetAttributeChangedSignal("InitialPosition"):Connect(attributeChanged)
See also:
Instance:SetAttribute(), sets the attribute with the given name to the given value
Instance:GetAttribute(), returns the attribute which has been assigned to the given name
Instance:GetAttributes(), returns a dictionary of string → variant pairs for each of the instance's attributes
Instance.AttributeChanged, fires whenever an attribute is changed on the instance
Parameters
attribute: string
The name of the specified attribute for which the change signal is being returned.
Returns
An event that fires when the given attribute changes.
GetAttributes
This function returns a dictionary of string → variant pairs for each attribute where the string is the name of the attribute and the variant is a non-nil value.
For example, the following code snippet will print an instance's attributes and values. Note that this code sample does not define Instance:
local attributes = instance:GetAttributes()
for name, value in pairs(attributes) do
print(name .. " " .. value)
end
See also:
Instance:SetAttribute(), sets the attribute with the given name to the given value
Instance:GetAttribute(), returns the attribute which has been assigned to the given name
Instance.AttributeChanged, fires whenever an attribute is changed on the instance
Instance:GetAttributeChangedSignal(), returns an event that fires when the given attribute changes
Returns
A dictionary of string → variant pairs for each attribute where the string is the name of the attribute and the variant is a non-nil value.
GetChildren
Returns an array (a numerically indexed table) containing all of the Instance's direct children, or every Instance whose Parent is equal to the object. The array can be iterated upon using either a numeric or generic for-loop:
-- Numeric for-loop example
local children = workspace:GetChildren()
for i = 1, #children do
local child = children[i]
print(child.Name .. " is child number " .. i)
end
-- Generic for-loop example
local children = workspace:GetChildren()
for i, child in ipairs(children) do
print(child.Name .. " is child number " .. i)
end
The children are sorted by the order in which their Parent property was set to the object.
See also the GetDescendants function.
Returns
An array containing the Instance's children.
Code Samples
The below would print the name of all objects currently in Workspace when ran.
Instance:GetChildren
local children = workspace:GetChildren()
for i = 1, #children do
print(i, children[i].Name)
end
GetDebugId
Not Browsable
Plugin Security
Returns a coded string of the Instances DebugId used internally by Roblox.
Note:
This item is protected. Attempting to use it in a Script or LocalScript will cause an error
A debug ID is an ID used in debugging processes. It allows a debugger to read each instruction before an application processes it. All objects in Roblox act like processes and each run instructions (or 'code') that can be debugged if needed
This can be helpful for plugins which need to distinguish similar objects from one-another (such as objects that share the same name)
Parameters
scopeLength: number
The scope length.
Default Value: 4
Returns
The Debug ID string.
Code Samples
Instance:GetDebugId
print(workspace:GetDebugId()) --> 39FA_12
print(workspace:GetDebugId(10)) --> 39FA2FEF4D_12
print(workspace:GetDebugId(math.huge)) --> 12
GetDescendants
Custom Lua State
The GetDescendants function of an object returns an array that contains all of the descendants of that object. Unlike Instance:GetChildren(), which only returns the immediate children of an object, GetDescendants will find every child of the object, every child of those children, and so on.
The arrays returned by GetDescendants are arranged so that parents come earlier than their children. Refer to the following example of a Model in the Workspace:
Inside this model are three parts (C, D, and E) and another model (InnerModel). Inside the inner model are two more parts (A and B). Calling GetDescendants on the first model and printing the contents of the returned array would print the first level of children (InnerModel, C, D, and E) before A and B.
local descendants = game.Workspace.Model:GetDescendants()
-- Loop through all of the descendants of the model and
-- print out their name
for index, descendant in pairs(descendants) do
print(descendant.Name)
end
-- Prints:
-- C
-- D
-- E
-- InnerModel
-- A
-- B
Returns
An array containing the Instance's descendants.
Code Samples
GetDescendants is often used to do something to all the descendants that are a particular type of object. The code in this example uses GetDescendants and Instance:IsA() to find all of the parts in the workspace and turns them green.
Instance:GetDescendants
local descendants = workspace:GetDescendants()
-- Loop through all of the descendants of the Workspace. If a
-- BasePart is found, the code changes that parts color to green
for _, descendant in pairs(descendants) do
if descendant:IsA("BasePart") then
descendant.BrickColor = BrickColor.Green()
end
end
GetFullName
Returns a string describing the Instance's ancestry. The string is a concatenation of the Name of the object and its ancestors, separated by periods. The DataModel (game) is not considered. For example, a Part in the Workspace may return Workspace.Part.
When called on an Instance that is not a descendant of the DataModel, this function considers all ancestors up to and including the topmost one without a Parent.
This function is useful for logging and debugging. You shouldn't attempt to parse the returned string for any useful operation; this function does not escape periods (or any other symbol) in object names. In other words, although its output often appears to be a valid Lua identifier, it is not guaranteed.
Returns
The full name of the Instance.
Code Samples
This code sample demonstrates the behavior of Instance:GetFullName(). It shows how the function behaves when called on an object not in the DataModel hierarchy, and it also shows how the return value does not escape special characters.
Instance:GetFullName
-- Create a simple hierarchy
local model = Instance.new("Model")
local part = Instance.new("Part")
part.Parent = model
local fire = Instance.new("Fire")
fire.Parent = part
print(fire:GetFullName()) --> Model.Part.Fire
model.Parent = workspace
print(fire:GetFullName()) --> Workspace.Model.Part.Fire
part.Name = "Hello, world"
print(fire:GetFullName()) --> Workspace.Model.Hello, world.Fire
This code sample re-implements the Instance:GetFullName() function in Lua.
Instance:GetFullName Lua Implementation
local function getFullName(object)
local result = object.Name
object = object.Parent
while object and object ~= game do
-- Prepend parent name
result = object.Name .. "." .. result
-- Go up the hierarchy
object = object.Parent
end
return result
end
print(getFullName(workspace.Camera)) --> Workspace.Camera
GetPropertyChangedSignal
This method returns an event that behaves exactly like the Changed event, except that the event only fires when the given property changes. It's generally a good idea to use this method instead of a connection to Changed with a function that checks the property name. Subsequent calls to this method on the same object with the same property name return the same event.
print(object:GetPropertyChangedSignal("Name") == object:GetPropertyChangedSignal("Name")) --> always true
ValueBase objects, such as IntValue and StringValue, use a modified Changed event that fires with the contents of the Value property. As such, this method provides a way to detect changes in other properties of those objects. For example, to detect changes in the Name property of an IntValue, use IntValue:GetPropertyChangedSignal("Name"):Connect(someFunc) since the Changed event of IntValue objects only detect changes on the Value property.
Parameters
property: string
The property to connect to.
Returns
A signal that fires whenever the property changes.
Code Samples
This code sample demonstrates how to save a value before a changed event fires on it in order to get more information about a change.
Old-to-New Values with Changed
local part = Instance.new("Part")
local currentColor = part.BrickColor
local function onBrickColorChanged()
local newColor = part.BrickColor
print("Color changed from", currentColor.Name, "to", newColor.Name)
currentColor = newColor
end
part:GetPropertyChangedSignal("BrickColor"):Connect(onBrickColorChanged)
part.BrickColor = BrickColor.new("Really red")
part.BrickColor = BrickColor.new("Really blue")
This code sample demonstrates the equivalence of the Changed event and event returned by GetPropertyChangedSignal.
Changed and GetPropertyChangedSignal
local part = Instance.new("Part")
local function onBrickColorChanged()
print("My color is now " .. part.BrickColor.Name)
end
local function onChanged(property)
if property == "BrickColor" then
onBrickColorChanged()
end
end
part:GetPropertyChangedSignal("BrickColor"):Connect(onBrickColorChanged)
part.Changed:Connect(onChanged)
-- Trigger some changes (because we connected twice,
-- both of these will cause two calls to onBrickColorChanged)
part.BrickColor = BrickColor.new("Really red")
part.BrickColor = BrickColor.new("Institutional white")
GetTags
This method returns an array of the tags applied to the given instance, as strings. You can add tags either in Studio in the Properties window or at runtime with AddTag().
This method is useful when you want to do something with multiple tags on an instance at once. However, it is inefficient to use this method to check for the existence of a single tag; instead, use HasTag() to check for a specific tag.
Returns
HasTag
This method returns true if the provided tag has been added to the object. You can add tags either in Studio in the Properties window or at runtime with AddTag().
Parameters
tag: string
Returns
IsA
Custom Lua State
IsA returns true if the Instance's class is equivalent to or a subclass of a given class. This function is similar to the instanceof operators in other languages, and is a form of type introspection. To ignore class inheritance, test the ClassName property directly instead. For checking native Lua data types (number, string, etc) use the functions type and typeof.
Most commonly, this function is used to test if an object is some kind of part, such as Part or WedgePart, which inherits from BasePart (an abstract class). For example, if your goal is to change all of a Character's limbs to the same color, you might use GetChildren to iterate over the children, then use IsA to filter non-BasePart objects which lack the BrickColor property:
local function paintFigure(character, color)
-- Iterate over the child objects of the character
for _, child in pairs(character:GetChildren()) do
-- Filter out non-part objects, such as Shirt, Pants and Humanoid
-- R15 use MeshPart and R6 use Part, so we use BasePart here to detect both:
if child:IsA("BasePart") then
child.BrickColor = color
end
end
end
paintFigure(game.Players.Player.Character, BrickColor.new("Bright blue"))
Since all classes inherit from Instance, calling object:IsA("Instance") will always return true.
Parameters
className: string
The class against which the Instance's class will be checked. Case-sensitive.
Returns
Describes whether the Instance's class matched or is a subclass of the given class.
Code Samples
Usage of IsA to test class inheritance:
Instance:IsA
print(workspace:IsA("Instance")) --> true
print(workspace:IsA("Workspace")) --> true
print(game:IsA("workspace")) --> false
print(game:IsA("DataModel")) --> true
IsAncestorOf
Returns true if an Instance is an ancestor of the given descendant.
An Instance is considered the ancestor of an object if the object's Instance.Parent or one of it's parent's Instance.Parent is set to the Instance.
See also, Instance:IsDescendantOf().
Parameters
descendant: Instance
The descendant Instance.
Returns
True if the Instance is an ancestor of the given descendant.
Code Samples
Instance:IsAncestorOf
print(workspace:IsAncestorOf(workspace.Player.HumanoidRootPart)) --> true
IsDescendantOf
Returns true if an Instance is a descendant of the given ancestor.
An Instance is considered the descendant of an object if the Instance's parent or one of its parent's parent is set to the object.
Note, DataModel is a descendant of nil. This means IsDescendantOf cannot be used with a parameter of nil to check if an object has been removed.
See also, Instance:IsAncestorOf().
Parameters
ancestor: Instance
The ancestor Instance.
Returns
True if the Instance is a descendant of the given ancestor.
Code Samples
Instance:IsDescendantOf
local part = Instance.new("Part")
print(part:IsDescendantOf(game))
--> false
part.Parent = workspace
print(part:IsDescendantOf(game))
--> true
part.Parent = game
print(part:IsDescendantOf(game))
--> true
Remove
void
DEPRECATED
DEPRECATED
This item is deprecated in favor of Instance:Destroy() and Instance:ClearAllChildren(). If you must remove an object from the game, and wish to use the object later, set its Parent property to nil instead of using this method.
The Remove function sets the object's Instance.Parent to nil, and does the same for all its descendants.
If the object is referenced before being removed it is possible to retrieve the object at a later point.
Returns
void
Code Samples
The following code demonstrates how a part can be re-added to the DataModel after being removed:
Instance:Remove
local part = Instance.new("Part")
part.Parent = workspace
print(part.Parent) --> Workspace
part:Remove()
print(part.Parent) --> nil
part.Parent = workspace
print(part.Parent) --> Workspace
RemoveTag
void
This method removes a tag from an instance. It will not throw an error if the object does not have the tag. Successfully removing a tag will fire a signal created by CollectionService:GetInstanceRemovedSignal() with the given tag.
Note that when tagging an instance, it's common that some resources are used to give the tag its functionality, for example event connections or tables. To prevent memory leaks, it's a good idea to clean these up (disconnect, set to nil, etc.) when no longer needed for a tag.
Parameters
tag: string
Returns
void
SetAttribute
void
This function sets the attribute with the given name to the given value. If the value given is nil, then the attribute will be removed (since nil is returned by default).
For example, the following code snippet will set the instance's InitialPosition attribute to Vector3.new(0, 0, 0). Note that this code sample does not define Instance:
instance:SetAttribute("InitialPosition", Vector3.new(0, 0, 0))
Limitations
Naming requirements and restrictions:
Names must only use alphanumeric characters and underscore
No spaces or unique symbols are allowed
Strings must be 100 characters or less
Names are not allowed to start with RBX unless the caller is a Roblox core-script (reserved for Roblox)
When attempting to set an attribute to an unsupported type, an error will be thrown.
See also:
Instance:GetAttribute(), returns the attribute which has been assigned to the given name
Instance:GetAttributes(), returns a dictionary of string → variant pairs for each of the instance's attributes
Instance.AttributeChanged, fires whenever an attribute is changed on the instance
Instance:GetAttributeChangedSignal(), returns an event that fires when the given attribute changes
Parameters
attribute: string
The name of the attribute being set.
value: Variant
The value that the specified attribute is being set to.
Returns
void
WaitForChild
Custom Lua State
Can Yield
Returns the child of the Instance with the given name. If the child does not exist, it will yield the current thread until it does. If the timeOut parameter is specified, this method will time out after the specified number of seconds and return nil.
Primary Usage
WaitForChild() is extremely important when working on code run by the client in a LocalScript. The Roblox engine does not guarantee the time or order in which objects are replicated from the server to the client. Additionally, if an experience has Workspace.StreamingEnabled set to true, BaseParts that are far away from the player's character may not be streamed to the client, potentially causing scripts to break when indexing objects that do not yet exist on the client.
Notes
This function does not yield if a child with the given name exists when the call is made.
Instance:FindFirstChild() is a more efficient alternative to WaitForChild() for objects that are assumed to exist.
If a call to this method exceeds 5 seconds without returning, and no timeOut parameter has been specified, a warning will be printed to the output that the thread may yield indefinitely. This warning takes the following form where X is the parent's name and Y is the child's name:
Infinite yield possible on 'X:WaitForChild("Y")'
Parameters
childName: string
The Instance.Name to be looked for.
timeOut: number
An optional time out parameter.
Returns
The Instance found.
Code Samples
The following code waits for an instance named "Part" to be added to Workspace.
Instance:WaitForChild
local part = workspace:WaitForChild("Part")
print(part.Name .. " has been added to the Workspace")
children
DEPRECATED
DEPRECATED
This item has been superseded by Instance:GetChildren() which should be used in all new work.
The children function returns an array of the object's children.
Returns
Array of child objects/instances.
clone
DEPRECATED
DEPRECATED
This deprecated function is a variant of Instance:Clone() which should be used instead.
Returns
destroy
void
DEPRECATED
DEPRECATED
This deprecated function is a variant of Instance:Destroy() which should be used instead.
Returns
void
findFirstChild
DEPRECATED
DEPRECATED
This deprecated function is a variant of Instance:FindFirstChild() which should be used instead.
Parameters
name: string
recursive: boolean
Default Value: false
Returns
getChildren
DEPRECATED
DEPRECATED
This deprecated function is a variant of Instance:GetChildren() which should be used instead.
Returns
isA
DEPRECATED
Custom Lua State
DEPRECATED
This deprecated function is a variant of Instance:IsA() which should be used instead.
Parameters
className: string
Returns
isDescendantOf
DEPRECATED
DEPRECATED
This deprecated function is a variant of Instance:IsDescendantOf() which should be used instead.
Parameters
ancestor: Instance
Returns
remove
void
DEPRECATED
DEPRECATED
This deprecated function is a variant of Instance:Remove() which has also been deprecated. Neither function should be used in new work.
Returns
void
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, 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
This code sample demonstrates the usage of Players.PlayerAdded, Player.CharacterAdded and Player.CharacterRemoving in order to detect the spawning and despawning of players' characters. You can use this as a boilerplate script to make changes to players' characters as they spawn, such as changing Humanoid.WalkSpeed.
Detecting Player Spawns and Despawns
local Players = game:GetService("Players")
local function onCharacterAdded(character)
print(character.Name .. " has spawned")
end
local function onCharacterRemoving(character)
print(character.Name .. " is despawning")
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
player.CharacterRemoving:Connect(onCharacterRemoving)
end
Players.PlayerAdded:Connect(onPlayerAdded)
This code sample will cause players to respawn at the same place they died. It does this by keeping track of where the player despawned using Player.CharacterRemoving. Note that the player's location is saved on-despawn, not on-death. This can be problematic if the player falls off a ledge and dies due to Workspace.FallenPartsDestroyHeight - their respawn position won't be saved in this case.
It's also important to note the need to "forget" the location of players who leave the game. We use Instance.ChildRemoved on Players instead of Players.PlayerRemoving. This is because PlayerRemoving fires before CharacterRemoving - and we need to make sure we don't forget the player's respawn location then immediately remember a new one (this is a memory leak; potentially many players could visit, respawn and leave). So, we use ChildRemoved on Players so the event fires after the character is removed.
Respawn at Despawn Location
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
-- This table maps "Player" objects to Vector3
local respawnLocations = {}
local function onCharacterAdded(character)
local player = Players:GetPlayerFromCharacter(character)
-- Check if we saved a respawn location for this player
if respawnLocations[player] then
-- Teleport the player there when their HumanoidRootPart is available
local hrp = character:WaitForChild("HumanoidRootPart")
-- Wait a brief moment before teleporting, as Roblox will teleport the
-- player to their designated SpawnLocation (which we will override)
RunService.Stepped:wait()
hrp.CFrame = CFrame.new(respawnLocations[player] + Vector3.new(0, 3.5, 0))
end
end
local function onCharacterRemoving(character)
-- Get the player and their HumanoidRootPart and save their death location
local player = Players:GetPlayerFromCharacter(character)
local hrp = character:FindFirstChild("HumanoidRootPart")
if hrp then
respawnLocations[player] = hrp.Position
end
end
local function onPlayerAdded(player)
-- Listen for spawns/despawns
player.CharacterAdded:Connect(onCharacterAdded)
player.CharacterRemoving:Connect(onCharacterRemoving)
end
local function onPlayerRemoved(player)
-- Forget the respawn location of any player who is leaving; this prevents
-- a memory leak if potentially many players visit
respawnLocations[player] = nil
end
-- Note that we're NOT using PlayerRemoving here, since CharacterRemoving fires
-- AFTER PlayerRemoving, we don't want to forget the respawn location then instantly
-- save another right after
Players.PlayerAdded:Connect(onPlayerAdded)
Players.ChildRemoved:Connect(onPlayerRemoved)
This code sample automatically removes Accessory objects like hats from the Player's character when they respawn. Warning: this includes hair, so this script may cause acute baldness.
When the Character() is added, we wait for RunService.Stepped to fire once (using the wait function of events). This is so the accessory removal logic runs one frame after the character spawns. A warning can appear if you delete accessories too quickly after the player spawns, so waiting one frame will avoid that.
Accessory Remover
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local function destroyAccessory(object)
if object:IsA("Hat") or object:IsA("Accessory") then
object:Destroy()
end
end
local function onCharacterAdded(character)
-- Wait a brief moment before removing accessories to avoid the
-- "Something unexpectedly set ___ parent to NULL" warning
RunService.Stepped:Wait()
-- Check for any existing accessories in the player's character
for _, child in pairs(character:GetChildren()) do
destroyAccessory(child)
end
-- Hats may be added to the character a moment after
-- CharacterAdded fires, so we listen for those using ChildAdded
character.ChildAdded:Connect(destroyAccessory)
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(onCharacterAdded)
end
Players.PlayerAdded:Connect(onPlayerAdded)
CharacterAppearanceLoaded
This event fires when the full appearance of a Player.Character has been inserted.
A Player.Character generally has a range of objects modifying its 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 ensure all accessories have loaded before destroying them. See below for an example of this.
Parameters
character: Model
The Player.Character Model.
Code Samples
This code sample will wait for accessories to fully load, print out how many there are, and then destroy them all.
Remove Accessories After Loading
local Players = game:GetService("Players")
local function onPlayerAddedAsync(player)
local connection = player.CharacterAppearanceLoaded:Connect(function(character)
-- All accessories have loaded at this point
local numAccessories = #character:GetAccessories()
print(("Destroying %d accessories for %s"):format(numAccessories, player.Name))
local humanoid = character:FindFirstChildOfClass("Humanoid")
humanoid:RemoveAccessories()
end)
-- Make sure we disconnect our connection to the player after they leave
-- to allow the player to get garbage collected
player.AncestryChanged:Wait()
connection:Disconnect()
end
for _, player in Players:GetPlayers() do
task.spawn(onPlayerAddedAsync, player)
end
Players.PlayerAdded:Connect(onPlayerAddedAsync)
CharacterRemoving
The CharacterRemoving event fires right before a player's character 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 to print a message every time a player spawns and dies:
local Players = game:GetService("Players")
local function onCharacterSpawned(player)
print(player.Name .. " is spawning")
end
local function onCharacterDespawned(player)
print(player.Name .. " is despawning")
end
local function onPlayerAdded(player)
player.CharacterAdded:Connect(function ()
onCharacterDespawned(player)
end)
player.CharacterRemoving:Connect(function ()
onCharacterDespawned(player)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
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
This example prints the name of the character being removed, followed by "has died".
For instance, if Shedletsky's character was to die in-game, "Shedletsky has died." would be printed.
Player.CharacterRemoving
game.Players.PlayerAdded:Connect(function(player)
player.CharacterRemoving:Connect(function(character)
print(character.Name .. " has died.")
end)
end)
Chatted
The Chatted event fires when a Player types a message and 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
Setting chatted for all players. There is an easy way to make the Chatted event registered on all players. Simply use the Players.PlayerAdded event in combination with this event.
Player.Chatted
local Players = game:GetService("Players")
local function onPlayerAdded(player)
local function onChatted(message)
-- do stuff with message and player
print(message)
end
player.Chatted:Connect(onChatted)
end
Players.PlayerAdded:Connect(onPlayerAdded)
This code sample, although lengthy, is quite simple: detect when a player chats /play, then put them on the "Playing" team. When they die, move them back to the "Spectating" team.
Playing/Spectating Teams
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
local teamPlaying = Teams.Playing
local teamSpectators = Teams.Spectating
local playCommand = "/play"
local function play(player)
player.Team = teamPlaying
player.TeamColor = teamPlaying.TeamColor
-- Respawn the player (moves them to spawn location)
player:LoadCharacter()
end
local function onPlayerDied(player, _character)
-- When someone dies, put them on the spectator team
player.Team = teamSpectators
end
local function onPlayerSpawned(player, character)
local human = character:WaitForChild("Humanoid")
human.Died:Connect(function()
onPlayerDied(player, character)
end)
end
local function onPlayerChatted(player, message)
if message:sub(1, playCommand:len()):lower() == playCommand then
play(player)
end
end
local function onPlayerAdded(player)
if player.Character then
onPlayerSpawned(player, player.Character)
end
player.CharacterAdded:Connect(function()
onPlayerSpawned(player, player.Character)
end)
player.Chatted:Connect(function(message, _recipient)
onPlayerChatted(player, message)
end)
end
for _, player in pairs(Players:GetPlayers()) do
onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)
This code sample allows any player to chat "/jointeam " where is the name of a team. It uses string manipulation using string.sub and string.lower to make the command case-insensitive and allow for partial matches. For example, "/jointeam red" will match the team "Red Robins".
Join Team Command
local Players = game:GetService("Players")
local Teams = game:GetService("Teams")
-- Command to choose a team (note the trailing space)
local joinCommand = "/jointeam "
local function findTeamByName(name)
-- First, check for the exact name of a team
if Teams:FindFirstChild(name) then
return Teams[name]
end
-- Let's check for case-insensitive partial matches, like "red" for "Red Robins"
for _, team in pairs(Teams:GetChildren()) do
if team.Name:sub(1, name:len()):lower() == name:lower() then
return team
end
end
-- If we get to this point, no team matched the one we were looking for :(
end
local function onPlayerChatted(player, message, _recipient)
-- Note: string.sub(message, ...) is the same as message:sub(...)
if message:sub(1, joinCommand:len()):lower() == joinCommand:lower() then
-- Matched "/JOINTEAM xyz" to our join command prefix "/jointeam "
local teamName = message:sub(joinCommand:len() + 1) -- Cut out the "xyz" from "/jointeam xyz"
local team = findTeamByName(teamName)
if team then
-- Set the team!
player.Team = team
player.Neutral = false
else
-- Tell the player that team could not be found :(
player.Team = nil
player.Neutral = true
end
end
end
local function onPlayerAdded(player)
player.Chatted:Connect(function(...)
onPlayerChatted(player, ...)
end)
end
Players.PlayerAdded:Connect(onPlayerAdded)
Idled
This event 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, consider using Players.PlayerRemoving alongside this event.
Parameters
time: number
The time in seconds the player has been idle.
Code Samples
This example will print how long a player, named Player, has been idle for.
Player.Idled1
local Players = game:GetService("Players")
local function onPlayerAdded(player)
local function onIdled(time)
print("Player has been idle for " .. time .. " seconds")
end
player.Idled:Connect(onIdled)
end
Players.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
This example prints which stage of a teleport a player is at, as well as printing if the teleport was a failure.
Player.OnTeleport
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local playerOnTeleport = player
player.OnTeleport:Connect(function(teleportState, _placeId, _spawnName)
if teleportState == Enum.TeleportState.Started then
print("Teleport started (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.WaitingForServer then
print("Teleport waiting for server (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.InProgress then
print("Teleport in progress (" .. playerOnTeleport.Name .. ")")
elseif teleportState == Enum.TeleportState.Failed then
print("Teleport failed! (" .. playerOnTeleport.Name .. ")")
end
end)
end)
Events inherited from Instance
AncestryChanged
Fires when the Instance.Parent property of the object or one of its ancestors is changed.
This event includes two parameters, child and parent. Child refers to the Instance whose Instance.Parent was actually changed. Parent refers to this Instance's new Instance.Parent.
You can use this event to track the deletion of an instance in Studio, such as manual deletion in the Explorer or through a plugin. If you need to detect when an instance is destroyed using Instance:Destroy(), use the Instance.Destroying event instead.
Parameters
child: Instance
The Instance whose Instance.Parent has been changed.
parent: Instance
The new Instance.Parent of the Instance whose Instance.Parent was changed.
Code Samples
The below example would print "Part is now a child of Model".
Instance.AncestryChanged
local part = Instance.new("Part")
part.Parent = workspace
local function onAncestryChanged(child, parent)
print(child.Name .. " is now a child of " .. parent.Name)
end
part.AncestryChanged:Connect(onAncestryChanged)
part.Parent = workspace.Model
AttributeChanged
This event fires whenever an attribute is changed on the instance. This includes when an attribute is set to nil. The name of the attribute that has been changed is passed to the connected function.
For example, the following code snippet will connect the AttributeChanged function to fire whenever one of Instance's attributes changes. Note that this code sample does not define Instance:
local function attributeChanged(attributeName)
print(attributeName, "changed")
end
instance.AttributeChanged:Connect(attributeChanged)
See also:
Instance:SetAttribute(), sets the attribute with the given name to the given value
Instance:GetAttribute(), returns the attribute which has been assigned to the given name
Instance:GetAttributes(), returns a dictionary of string → variant pairs for each of the instance's attributes
Instance:GetAttributeChangedSignal(), returns an event that fires when the given attribute changes
Parameters
attribute: string
The name of the attribute that has been changed.
Changed
The Changed event fires right after most properties change on objects. It is possible to find the present value of a changed property by using object[property]. To get the value of a property before it changes, you must have stored the value of the property before it changed.
If you are only interested in listening to the change of a specific property, consider using the GetPropertyChangedSignal method instead to get an event that only fires when a given property changes.
This event does not fire for physics-related changes, like when the CFrame, Velocity, RotVelocity, Position, Orientation and CFrame properties of a BasePart change due to gravity. To detect changes in these properties, consider using a physics-based event like RunService.Stepped or BasePart.Touched. A while-true-do loop can also work.
For "-Value" objects, this event behaves differently: it only fires when the Value property changes. See individual pages for IntValue, StringValue, etc for more information. To detect other changes in these objects, you must use GetPropertyChangedSignal instead.
Parameters
property: string
The name of the property that changed.
Code Samples
This sample demonstrates the subtleties of the Changed event on normal objects and "-Value" objects.
Changed Event
-- Demonstrate the Changed event by creating a Part
local part = Instance.new("Part")
part.Changed:Connect(print)
-- This fires Changed with "Transparency"
part.Transparency = 0.5
-- Similarly, this fires Changed with "Number"
part.Name = "SomePart"
-- Since changing BrickColor will also change other
-- properties at the same time, this line fires Changed
-- with "BrickColor", "Color3" and "Color3uint16".
part.BrickColor = BrickColor.Red()
-- A NumberValue holds a double-precision floating-point number
local vNumber = Instance.new("NumberValue")
vNumber.Changed:Connect(print)
-- This fires Changed with 123.456 (not "Value")
vNumber.Value = 123.456
-- This does not fire Changed
vNumber.Name = "SomeNumber"
-- A StringValue stores one string
local vString = Instance.new("StringValue")
vString.Changed:Connect(print)
-- This fires Changed with "Hello" (not "Value")
vString.Value = "Hello"
This code sample demonstrates the Changed event firing within a parent object.
Change Detector
local object = script.Parent
local function onChanged(property)
-- Get the current value of the property
local value = object[property]
-- Print a message saying what changed
print(object:GetFullName() .. "." .. property .. " (" .. typeof(value) .. ") changed to " .. tostring(value))
end
object.Changed:Connect(onChanged)
-- Trigger a simple change in the object (add an underscore to the name)
object.Name = "_" .. object.Name
ChildAdded
Fires after an object is parented to this Instance.
Note, when using this function on a client to detect objects created by the server it is necessary to use Instance:WaitForChild() when indexing these object's descendants. This is because the object and its descendants are not guaranteed to replicate from the server to the client simultaneously. For example:
workspace.ChildAdded:Connect(function(child)
-- need to use WaitForChild as descendants may not have replicated yet
local head = child:WaitForChild("Head")
end)
Note, this function only works for immediate children of the Instance. For a function that captures all descendants, use Instance.DescendantAdded.
See also, Instance.ChildRemoved.
Parameters
child: Instance
The Instance that has been added.
Code Samples
This snippet prints the names of objects as they are added to the Workspace:
Instance.ChildAdded
local function onChildAdded(instance)
print(instance.Name .. " added to the workspace")
end
workspace.ChildAdded:Connect(onChildAdded)
local part = Instance.new("Part")
part.Parent = workspace --> Part added to the Workspace
ChildRemoved
Fires after a child is removed from this Instance.
Removed refers to when an object's parent is changed from this Instance to something other than this Instance. Note, this event will also fire when a child is destroyed (using Instance:Destroy()) as the destroy function sets an object's parent to nil.
This function only works for immediate children of the Instance. For a function that captures all descendants, use Instance.DescendantRemoving.
See also Instance.ChildAdded.
Parameters
child: Instance
The Instance that has been removed.
Code Samples
This snippet prints the names of objects as they are removed from the Workspace:
Instance.ChildRemoved
local function onChildRemoved(instance)
print(instance.Name .. " removed from the workspace")
end
workspace.ChildRemoved:Connect(onChildRemoved)
local part = Instance.new("Part")
part.Parent = workspace
task.wait(2)
part:Destroy()
DescendantAdded
The DescendantAdded event fires after a descendant is added to the Instance.
As DescendantAdded fires for every descendant, parenting an object to the Instance will fire the event for this object and all of its descendants individually.
Developers only concerned with the immediate children of the Instance should use Instance.ChildAdded instead.
See also Instance.DescendantRemoving.
Parameters
descendant: Instance
The Instance that has been added.
Code Samples
This following example will print the name of any object that is added to the Workspace:
Instance.DescendantAdded
local function onDescendantAdded(descendant)
print(descendant)
end
workspace.DescendantAdded:Connect(onDescendantAdded)
local part = Instance.new("Part")
part.Parent = workspace
DescendantRemoving
DescendantRemoving fires immediately before the Parent of a descendant of the Instance changes such that the object is no longer a descendant of the Instance. Destroy and Remove change an object's Parent to nil, so calling these on a descendant of an object will therefore cause this event to fire.
Since this event fires before the descendant's removal, the Parent of the descendant will be unchanged, i.e., it will still be a descendant at the time of this event firing. If the descendant is also a child of the object, It will also fire before ChildRemoved. There is no similar event called "DescendantRemoved".
If a descendant has children, this event fires with the descendant first followed by its descendants.
Example
The example below should help clarify how DescendantRemoving fires when there are several objects involved.
Calling Remove on PartA would cause DescendantRemoving to fire on both ModelA and Model, in that order.
Setting the Parent of PartA to ModelB would cause DescendantRemoving to fire on ModelA but not Model (as Model would still be an ancestor of PartA).
Calling Destroy on ModelA would cause DescendantRemoving to fire multiple times on several objects:
On Model with ModelA, PartA then FireA.
On ModelA, with PartA then FireA.
On PartA with FireA.
Warning
This event fires with the descendant object that is being removed. Attempting to set the Parent of the descendant being removed to something else will fail with the following warning: "Something unexpectedly tried to set the parent of X to Y while trying to set the parent of X. Current parent is Z", where X is the removing descendant, Y is the ignored parent setting, and Z is the original parent of X. Below is an example that demonstrates this:
workspace.DescendantRemoving:Connect(function(descendant)
-- Don't manipulate the parent of descendant in this function!
-- This event fires BECAUSE the parent of descendant was manipulated,
-- and the change hasn't happened yet, i.e. this function fires before that happens.
-- Therefore, it is problematic to change the parent like this:
descendant.Parent = game
end)
local part = Instance.new("Part")
part.Parent = workspace
part.Parent = nil -- This triggers DescendantRemoving on Workspace:
--> Something unexpectedly tried to set the parent of Part to NULL while trying to set the parent of Part. Current parent is Workspace.
See also DescendantAdded.
Parameters
descendant: Instance
The Instance that is being removed.
Code Samples
The following example prints the name of any descendant as it is being removed from the Workspace:
Instance.DescendantRemoving
workspace.DescendantRemoving:Connect(function(descendant)
print(descendant.Name .. " is currently parented to " .. tostring(descendant.Parent))
end)
local part = Instance.new("Part")
part.Parent = workspace
part.Parent = nil
--> Part is currently parented to Workspace
print(part.Parent)
--> nil
Destroying
The Destroying event fires immediately before the Instance or one of its ancestors is destroyed with Instance.Destroy().
The Instance will never be deleted from memory while a connected function is still using it. However, if the function yields at any point, the Instance and its descendants will be parented to nil.
When deleting an instance in Studio, such as manually deleting through the Explorer or through a plugin, the instance isn't destroyed. Instead, the parent is set to nil which you can track with Instance.AncestryChanged.
Code Samples
This sample demonstrates how an Instance being destroyed remains in place until the connected function yields.
Using the Destroying Event
local part = Instance.new("Part", workspace)
local function onPartDestroying()
print("Before yielding:", part:GetFullName(), #part:GetChildren())
task.wait()
print("After yielding:", part:GetFullName(), #part:GetChildren())
end
part.Destroying:Connect(onPartDestroying)
part:Destroy()
childAdded
DEPRECATED
DEPRECATED
This deprecated event is a variant of Instance.ChildAdded which should be used instead.
Parameters
child: Instance




