mtx-roblox-ai / data /classes /Mouse.md
chaman-k
chore: Cleanup
1bc170b

A newer version of the Gradio SDK is available: 6.12.0

Upgrade

Mouse

Not Creatable

Mouse has been superseded by UserInputService and ContextActionService, which cover a broader scope, are more feature rich, and support cross-platform patterns better. It remains supported because of its widespread use, but you should strongly consider using these alternatives.

The Mouse object houses various API for pointers, primarily for buttons and raycasting. It can be accessed through Player:GetMouse() called on the Players.LocalPlayer in a LocalScript. It is also passed by the Tool.Equipped event.


-- From a LocalScript:
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
-- Setting the mouse icon
mouse.Icon = "rbxasset://SystemCursors/Wait"

Note:

Summary

Properties

Hit: CFrame

The CFrame of the mouse's position in 3D space.

READ ONLY

NOT REPLICATED

Icon: Content

The content ID of the image used as the Mouse's icon.

Origin: CFrame

A CFrame positioned at the Workspace.CurrentCamera and oriented toward the Mouse's 3D position.

READ ONLY

NOT REPLICATED

Target: BasePart

The object in 3D space the mouse is pointing to.

READ ONLY

NOT REPLICATED

TargetFilter: Instance

Determines an object (and its descendants) to be ignored when determining Mouse.Hit and Mouse.Target.

TargetSurface: NormalId

Indicates the NormalId of the BasePart surface at which the mouse is pointing.

READ ONLY

NOT REPLICATED

UnitRay: Ray

A Ray directed towards the Mouse's world position, originating from the Camera's world position.

READ ONLY

NOT REPLICATED

ViewSizeX: number

Describes the width of the game window in pixels.

READ ONLY

NOT REPLICATED

ViewSizeY: number

Describes the height of the game window in pixels.

READ ONLY

NOT REPLICATED

X: number

Describes the X (horizontal) component of the mouse's position on the screen.

READ ONLY

NOT REPLICATED

Y: number

Describes the Y (vertical) component of the mouse's screen position.

READ ONLY

NOT REPLICATED

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

Methods inherited from Instance

AddTag(tag: string): void  


Applies a tag to the instance.

ClearAllChildren(): void  


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.

Destroy(): void  


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.

HasTag(tag: string): boolean  


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.

Remove(): void  DEPRECATED


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


destroy(): void  DEPRECATED


findFirstChild(name: string, recursive: boolean): Instance  DEPRECATED


getChildren(): Objects  DEPRECATED


isA(className: string): boolean  DEPRECATED, CUSTOM LUA STATE


isDescendantOf(ancestor: Instance): boolean  DEPRECATED


remove(): void  DEPRECATED


Events

Button1Down(): RBXScriptSignal  


Fired when the left mouse button is pressed.

Button1Up(): RBXScriptSignal  


Fires when the left mouse button is released.

Button2Down(): RBXScriptSignal  


Fires when the right mouse button is pressed.

Button2Up(): RBXScriptSignal  


Fired when the right mouse button is released.

Idle(): RBXScriptSignal  


Fired during every heartbeat that the mouse isn't being passed to another mouse event.

Move(): RBXScriptSignal  


Fired when the mouse is moved.

WheelBackward(): RBXScriptSignal  


Fires when the mouse wheel is scrolled backwards.

WheelForward(): RBXScriptSignal  


Fires when the mouse wheel is scrolled forwards.

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

Hit

CFrame

Read Only

Not Replicated

Read Parallel

This property indicates CFrame of the mouse's position in 3D space. Note that Mouse.TargetFilter and its descendants will be ignored.

Developers can get obtain the position of Hit like so:


local position = mouse.Hit.p

Hit is often used by Tools to fire a weapon towards the mouse in third person.

Developers looking for the BasePart the mouse is pointing at should use Mouse.Target.

How is Mouse.Hit calculated?

The position of the Hit CFrame is calculated as the point of intersection between the mouse's internal Ray (an extended version of Mouse.UnitRay) and an object in 3D space (such as a part).

The orientation of the Hit CFrame corresponds with the direction of the Mouse.UnitRay.


local unitRayDirection = mouse.UnitRay.Direction
local mouseHitDirection = mouse.Hit.lookVector
-- unitRayDirection ≈ mouseHitDirection
-- the vectors are approximately equal

Note, the roll of the Workspace.CurrentCamera is not used when calculating the orientation of the Hit CFrame.

The mouse's internal ray extends for 1000 studs. If the mouse is not pointing at an object in 3D space (for example when pointing at the sky), this property will be 1000 studs away from the Workspace.CurrentCamera.

Code Samples

The code in this sample, when placed inside a LocalScript within StarterPlayerScripts will draw a red laser beam between the character's head and Mouse.Hit at all times.

Note, this beam will pass directly through obstructions in third person as the Mouse's raycasting is done from the Workspace.CurrentCamera not the head.

Mouse.Hit Laser Beam


local Players = game:GetService("Players")
local RunService = game:GetService("RunService")

local player = Players.LocalPlayer

local mouse = player:GetMouse()

local beam = Instance.new("Beam")
beam.Segments = 1
beam.Width0 = 0.2
beam.Width1 = 0.2
beam.Color = ColorSequence.new(Color3.new(1, 0, 0))
beam.FaceCamera = true

local attachment0 = Instance.new("Attachment")
local attachment1 = Instance.new("Attachment")
beam.Attachment0 = attachment0
beam.Attachment1 = attachment1

beam.Parent = workspace.Terrain
attachment0.Parent = workspace.Terrain
attachment1.Parent = workspace.Terrain

local function onRenderStep()
    local character = player.Character
    if not character then
        beam.Enabled = false
        return
    end

    local head = character:FindFirstChild("Head")
    if not head then
        beam.Enabled = false
        return
    end

    beam.Enabled = true

    local origin = head.Position
    local finish = mouse.Hit.Position

    attachment0.Position = origin
    attachment1.Position = finish
end

RunService.RenderStepped:Connect(onRenderStep)

The code below visualizes the difference between Mouse.Hit and Mouse.Origin. In order to do this, the code uses the Vector3 positions of the hit and origin CFrame values using .p.

The difference is that the origin is "where the mouse came from" (its origin) and the hit is the position where the mouse hits (is when the player presses their mouse).

This example also visualizes that the mouse origin is very similar to the position of the CurrentCamera by printing the magnitude (distance) between the two positions.

Mouse Origin vs Mouse Hit vs CurrentCamera Position


local Players = game:GetService("Players")

local mouse = Players.LocalPlayer:GetMouse()
local camPos = workspace.CurrentCamera.CFrame.Position

print("Mouse.Hit:", mouse.Hit.Position)
print("camPos:", camPos)
print("Mouse.Origin:", mouse.Origin.Position)
print("Magnitude:", (mouse.Origin.Position - camPos).Magnitude)

Icon

Content

Read Parallel

Icon is a property that determines the image used as the pointer. If blank, a default arrow is used. While the cursor hovers over a GuiButton, this property is temporarily ignored.

To hide the cursor entirely, do not use a transparent image – instead, set UserInputService.MouseIconEnabled to false.

For getting/setting the user mouse icon in experiences, you should use UserInputService.MouseIcon. Mouse.Icon will be deprecated after the new API for plugins to set the mouse cursor is released.

Designing a Cursor

The following guidelines may prove useful when creating your own mouse cursors:

  • The dimensions of the image used determines the size of the cursor.

  • The center of the image is where mouse inputs are issued.

  • The default mouse image is 64x64 pixels, with the mouse taking up 17x24 pixels of space.

System Cursors for PluginMouse

When using a PluginMouse retrieved from Plugin:GetMouse(), you can use the following icons similar to your system's default cursors, such as hands, arrows, I-beams, etc. You can use these with GUI events like MouseEnter, MouseLeave, and MouseButton1Down to provide a consistent studio experience when interacting with certain kinds of GUI components. Note that these only work for studio plugins; they will not work for other Mouse objects.

Look*

Asset

Suggested Use

rbxasset://SystemCursors/Arrow

Default clicking and selection.

rbxasset://SystemCursors/PointingHand

Hovering over an active link/button.

rbxasset://SystemCursors/OpenHand

Hovering over a draggable item.

rbxasset://SystemCursors/ClosedHand

Dragging an item.

rbxasset://SystemCursors/IBeam

Hovering in a text field.

rbxasset://SystemCursors/SizeNS

Hovering over a vertical resize handle.

rbxasset://SystemCursors/SizeEW

Hovering over a horizontal resize handle.

rbxasset://SystemCursors/SizeNESW

Hovering over a corner resize handle.

rbxasset://SystemCursors/SizeNWSE

Hovering over a corner resize handle.

rbxasset://SystemCursors/SizeAll

Hovering over a multi-direction resize handle.

rbxasset://SystemCursors/SplitNS

Hovering over a vertical "split" handle.

rbxasset://SystemCursors/SplitEW

Hovering over a horizontal "split" handle.

rbxasset://SystemCursors/Forbidden

Hovering over a locked/forbidden item.

rbxasset://SystemCursors/Wait

Indicating an action is in progress.

rbxasset://SystemCursors/Busy

Indicating the system is busy.

rbxasset://SystemCursors/Cross

Hovering over a pinpoint selection area.

* These appearances are approximations – the actual look is dependent on your operating system.

Code Samples

This example changes the Players.LocalPlayer mouse icon to look like the dragon image shown below.

Dragon mouse icon

Dragon Mouse Icon


local Players = game:GetService("Players")

local mouse = Players.LocalPlayer:GetMouse()
mouse.Icon = "http://www.roblox.com/asset?id=163023520"

Origin

CFrame

Read Only

Not Replicated

Read Parallel

The origin Mouse property is a CFrame indicating where the mouse originated from. It is positioned at the Workspace.CurrentCamera and oriented toward the Mouse's 3D position.

Mouse.UnitRay starts at the same position as Origin, and extends for a stud in the same direction.


local unitRay = mouse.UnitRay
local origin = mouse.Origin
-- unitRay.Direction = origin.p
-- unitRay.Direction ≈ origin.lookVector

For the position of the Mouse in 3D space, see Mouse.Hit.

Code Samples

The code below visualizes the difference between Mouse.Hit and Mouse.Origin. In order to do this, the code uses the Vector3 positions of the hit and origin CFrame values using .p.

The difference is that the origin is "where the mouse came from" (its origin) and the hit is the position where the mouse hits (is when the player presses their mouse).

This example also visualizes that the mouse origin is very similar to the position of the CurrentCamera by printing the magnitude (distance) between the two positions.

Mouse Origin vs Mouse Hit vs CurrentCamera Position


local Players = game:GetService("Players")

local mouse = Players.LocalPlayer:GetMouse()
local camPos = workspace.CurrentCamera.CFrame.Position

print("Mouse.Hit:", mouse.Hit.Position)
print("camPos:", camPos)
print("Mouse.Origin:", mouse.Origin.Position)
print("Magnitude:", (mouse.Origin.Position - camPos).Magnitude)

Target

BasePart

Read Only

Not Replicated

Read Parallel

The object in 3D space the mouse is pointing to.

Note:

  • If Mouse.TargetFilter has been set, the target filter and its descendants will be ignored.

  • When the mouse is not pointing at a BasePart, for example when it is pointing at the sky, Target will be nil.

  • Developers looking for the position of the mouse in 3D space should use Mouse.Hit.

Code Samples

The following code sample, when placed in StarterPlayerScripts will create a tool in the player's backpack that, once equipped, will change the BasePart.BrickColor of every BasePart the player clicks on.

Color Randomizer Tool


local Players = game:GetService("Players")

local localPlayer = Players.LocalPlayer
local backpack = localPlayer:WaitForChild("Backpack")

local tool = Instance.new("Tool")
tool.RequiresHandle = false
tool.CanBeDropped = false
tool.Parent = backpack

tool.Equipped:Connect(function(mouse)
    mouse.Button1Down:Connect(function()
        if mouse.Target and mouse.Target.Parent then
            mouse.Target.BrickColor = BrickColor.random()
        end
    end)
end)

TargetFilter

Instance

Read Parallel

This property determines an object to be ignored by the mouse when calculating Mouse.Hit and Mouse.Target. The descendants of the object are also ignored, so it is possible to ignore multiple objects so long as they are a descendant of the object to which this property is set. This property is useful when filtering models containing special effects or decorations that should not affect Mouse.Hit or Mouse.Target.

This property can be set to any Instance or nil, for example:


local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
mouse.TargetFilter = workspace.Model

Note that the Character of the Players.LocalPlayer is ignored by the mouse automatically.

TargetSurface

NormalId

Read Only

Not Replicated

Read Parallel

This property indicates the NormalId of the BasePart surface at which the mouse is pointing. This property is derived from the world position of mouse (Mouse.Hit) and the part toward which the mouse is pointing (Mouse.Target).

This property isn't meaningful when the mouse is not pointing at a part, for example when the mouse is pointing at the sky. At the moment, this property is set to 'Right' under these circumstances. Before using this property, check that the mouse's target is not nil.


local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
-- Check that there exists a part at which the mouse is pointing
if mouse.Target then
    print("The mouse is pointing to the " .. mouse.TargetSurface.Name .. " side of " .. mouse.Target.Name)
else
    print("The mouse is not pointing at anything.")
end

Code Samples

The code in this sample, when placed in a LocalScript inside StarterPlayerScripts will set the surface of any BasePart clicked on to a random surface.

Surface Randomizer


local Players = game:GetService("Players")

local player = Players.LocalPlayer

local mouse = player:GetMouse()

local surfaceTypes = {
    Enum.SurfaceType.Smooth,
    Enum.SurfaceType.Glue,
    Enum.SurfaceType.Weld,
    Enum.SurfaceType.Studs,
    Enum.SurfaceType.Inlet,
    Enum.SurfaceType.Universal,
    Enum.SurfaceType.Hinge,
    Enum.SurfaceType.Motor,
}

local function onMouseClick()
    -- make sure the mouse is pointing at a part
    local target = mouse.Target
    if not target then
        return
    end

    local surfaceType = surfaceTypes[math.random(1, #surfaceTypes)]

    local surface = mouse.TargetSurface
    local propertyName = surface.Name .. "Surface"

    mouse.Target[propertyName] = surfaceType
end

mouse.Button1Down:Connect(onMouseClick)

UnitRay

Ray

Read Only

Not Replicated

Read Parallel

The UnitRay property is a Ray directed toward the Mouse's position in 3D space (described by Mouse.Hit). It originates from the CFrame of the Workspace.CurrentCamera. Like all unit rays, it has a distance of 1.


local Players = game:GetService("Players")
local player = Players.LocalPlayer
local mouse = player:GetMouse()
print(mouse.UnitRay.Direction.magnitude) -- Always 1

ViewSizeX

number

Read Only

Not Replicated

Read Parallel

The ViewSizeX property describes the horizontal component of the game window's size in pixels.

Code Samples

This code sample shows how you can create a Vector2 representing the Mouse object's position on screen (X() and Y()) and the size of the screen itself (ViewSizeX() and ViewSizeY()). Using these, you can normalize the position of the mouse on-screen such that the top-left just under the topbar maps to (0, 0) and the bottom-right maps to (1, 1). This normalized position is calculated and printed as the mouse moves using the Move() event.

Normalized Mouse Position


local Players = game:GetService("Players")

-- Note: You should use ContextActionService or UserInputService instead of
-- the Mouse object for accomplishing this task.
local player = Players.LocalPlayer
local mouse = player:GetMouse()

local function onMouseMove()
    -- Construct Vector2 objects for the mouse's position and screen size
    local position = Vector2.new(mouse.X, mouse.Y)
    local size = Vector2.new(mouse.ViewSizeX, mouse.ViewSizeY)
    -- A normalized position will map the top left (just under the topbar)
    -- to (0, 0) the bottom right to (1, 1), and the center to (0.5, 0.5).
    -- This is calculated by dividing the position by the total size.
    local normalizedPosition = position / size
    print(normalizedPosition)
end
mouse.Move:Connect(onMouseMove)

ViewSizeY

number

Read Only

Not Replicated

Read Parallel

The ViewSizeY property describes the vertical component of the game window's size in pixels. This length includes the space used by the topbar.

Code Samples

This code sample shows how you can create a Vector2 representing the Mouse object's position on screen (X() and Y()) and the size of the screen itself (ViewSizeX() and ViewSizeY()). Using these, you can normalize the position of the mouse on-screen such that the top-left just under the topbar maps to (0, 0) and the bottom-right maps to (1, 1). This normalized position is calculated and printed as the mouse moves using the Move() event.

Normalized Mouse Position


local Players = game:GetService("Players")

-- Note: You should use ContextActionService or UserInputService instead of
-- the Mouse object for accomplishing this task.
local player = Players.LocalPlayer
local mouse = player:GetMouse()

local function onMouseMove()
    -- Construct Vector2 objects for the mouse's position and screen size
    local position = Vector2.new(mouse.X, mouse.Y)
    local size = Vector2.new(mouse.ViewSizeX, mouse.ViewSizeY)
    -- A normalized position will map the top left (just under the topbar)
    -- to (0, 0) the bottom right to (1, 1), and the center to (0.5, 0.5).
    -- This is calculated by dividing the position by the total size.
    local normalizedPosition = position / size
    print(normalizedPosition)
end
mouse.Move:Connect(onMouseMove)

X

number

Read Only

Not Replicated

Read Parallel

When detecting changes in the mouse's position on-screen, it is recommended that you use ContextActionService:BindAction() with UserInputType.MouseMovement or UserInputService.InputChanged, which both describe the position of the mouse using the Position (a Vector3) of an InputObject, instead of using this and related properties.

The X property describes the horizontal component of the mouse's position on the screen. The position is measured in pixels relative to the top left corner, under the topbar. This property can be used in conjunction with Mouse.Y to produce a Vector2 representing the mouse's position:


local position = Vector2.new(mouse.X, mouse.Y)

This property does not fire Changed or the signal returned from GetPropertyChangedSignal. Use the Mouse.Move event instead.

Code Samples

This code sample shows how you can create a Vector2 representing the Mouse object's position on screen (X() and Y()) and the size of the screen itself (ViewSizeX() and ViewSizeY()). Using these, you can normalize the position of the mouse on-screen such that the top-left just under the topbar maps to (0, 0) and the bottom-right maps to (1, 1). This normalized position is calculated and printed as the mouse moves using the Move() event.

Normalized Mouse Position


local Players = game:GetService("Players")

-- Note: You should use ContextActionService or UserInputService instead of
-- the Mouse object for accomplishing this task.
local player = Players.LocalPlayer
local mouse = player:GetMouse()

local function onMouseMove()
    -- Construct Vector2 objects for the mouse's position and screen size
    local position = Vector2.new(mouse.X, mouse.Y)
    local size = Vector2.new(mouse.ViewSizeX, mouse.ViewSizeY)
    -- A normalized position will map the top left (just under the topbar)
    -- to (0, 0) the bottom right to (1, 1), and the center to (0.5, 0.5).
    -- This is calculated by dividing the position by the total size.
    local normalizedPosition = position / size
    print(normalizedPosition)
end
mouse.Move:Connect(onMouseMove)

Y

number

Read Only

Not Replicated

Read Parallel

When detecting changes in the mouse's position on-screen, it is recommended that you use ContextActionService:BindAction() with UserInputType.MouseMovement or UserInputService.InputChanged, which both describe the position of the mouse using the Position (a Vector3) of an InputObject, instead of using this and related properties.

The Y property describes the vertical component of the mouse's position on the screen. The position is measured in pixels relative to the top left corner, under the topbar. This property can be used in conjunction with Mouse.X to produce a Vector2 representing the mouse's position:


local position = Vector2.new(mouse.X, mouse.Y)

This property does not fire Changed or the signal returned from GetPropertyChangedSignal. Use the Mouse.Move event instead.

Code Samples

This code sample shows how you can create a Vector2 representing the Mouse object's position on screen (X() and Y()) and the size of the screen itself (ViewSizeX() and ViewSizeY()). Using these, you can normalize the position of the mouse on-screen such that the top-left just under the topbar maps to (0, 0) and the bottom-right maps to (1, 1). This normalized position is calculated and printed as the mouse moves using the Move() event.

Normalized Mouse Position


local Players = game:GetService("Players")

-- Note: You should use ContextActionService or UserInputService instead of
-- the Mouse object for accomplishing this task.
local player = Players.LocalPlayer
local mouse = player:GetMouse()

local function onMouseMove()
    -- Construct Vector2 objects for the mouse's position and screen size
    local position = Vector2.new(mouse.X, mouse.Y)
    local size = Vector2.new(mouse.ViewSizeX, mouse.ViewSizeY)
    -- A normalized position will map the top left (just under the topbar)
    -- to (0, 0) the bottom right to (1, 1), and the center to (0.5, 0.5).
    -- This is calculated by dividing the position by the total size.
    local normalizedPosition = position / size
    print(normalizedPosition)
end
mouse.Move:Connect(onMouseMove)

Properties inherited from Instance

Archivable

boolean

Read Parallel

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

string

Read Only

Not Replicated

Read Parallel

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

string

Read Parallel

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

Instance

Not Replicated

Read Parallel

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

boolean

Hidden

Plugin Security

Read Parallel

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

boolean

Hidden

Not Replicated

DEPRECATED

Read Parallel

DEPRECATED

This deprecated property is a variant of Instance.Archivable which should be used instead.

className

string

Read Only

Not Replicated

DEPRECATED

Read Parallel

DEPRECATED

This deprecated property is a variant of Instance.ClassName which should be used instead.

Methods

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

Instance

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

Instance

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

Instance

Write Parallel

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

Instance

The Instance found.

FindFirstAncestorOfClass

Instance

Write Parallel

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

Instance

The Instance found.

FindFirstAncestorWhichIsA

Instance

Write Parallel

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

Instance

The Instance found.

FindFirstChild

Instance

Write Parallel

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

Instance

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

Instance

Write Parallel

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

Instance

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

Instance

Write Parallel

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

Instance

The Instance found.

FindFirstDescendant

Instance

Write Parallel

Returns the first descendant found with the given Instance.Name.

Parameters

name: string

The Instance.Name to search for.

Returns

Instance

The Instance found.

GetActor

Actor

Write Parallel

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

Actor

The Actor found.

GetAttribute

Variant

Write Parallel

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:

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

RBXScriptSignal

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:

Parameters

attribute: string

The name of the specified attribute for which the change signal is being returned.

Returns

RBXScriptSignal

An event that fires when the given attribute changes.

GetAttributes

table

Write Parallel

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:

Returns

table

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

Objects

Write Parallel

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

Objects

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

string

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

string

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

Array

Custom Lua State

Write Parallel

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:

Workspace Descendants

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

Array

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

string

Write Parallel

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

string

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

RBXScriptSignal

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

RBXScriptSignal

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

Array

Write Parallel

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

Array

HasTag

boolean

Write Parallel

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

boolean

IsA

boolean

Custom Lua State

Write Parallel

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

boolean

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

boolean

Write Parallel

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

boolean

True if the Instance is an ancestor of the given descendant.

Code Samples

Instance:IsAncestorOf


print(workspace:IsAncestorOf(workspace.Player.HumanoidRootPart)) --> true

IsDescendantOf

boolean

Write Parallel

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

boolean

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:

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

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. 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

Instance

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

Objects

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

Objects

Array of child objects/instances.

clone

Instance

DEPRECATED

DEPRECATED

This deprecated function is a variant of Instance:Clone() which should be used instead.

Returns

Instance

destroy

void

DEPRECATED

DEPRECATED

This deprecated function is a variant of Instance:Destroy() which should be used instead.

Returns

void

findFirstChild

Instance

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

Instance

getChildren

Objects

DEPRECATED

DEPRECATED

This deprecated function is a variant of Instance:GetChildren() which should be used instead.

Returns

Objects

isA

boolean

DEPRECATED

Custom Lua State

DEPRECATED

This deprecated function is a variant of Instance:IsA() which should be used instead.

Parameters

className: string

Returns

boolean

isDescendantOf

boolean

DEPRECATED

DEPRECATED

This deprecated function is a variant of Instance:IsDescendantOf() which should be used instead.

Parameters

ancestor: Instance

Returns

boolean

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

Button1Down

The Button1Down even fires when the player presses their left mouse button.

This can also be accessed from a Tool. For example, when placed in a LocalScript, the code below prints Button1Down whenever the left mouse button is pressed:


local Tool = script.Parent --make sure this is a Tool object

Tool.Equipped:Connect(function(Mouse)
    Mouse.Button1Down:Connect(function()
        print("Button1Down")
    end)
end)

Developers can find out the position of the mouse in world-space, and if it is pointing at any BasePart, using the Mouse.Hit and Mouse.Target properties.

For information on how to obtain the mouse object, please see the Mouse page.

Note, developers are recommended to use UserInputService instead of the Mouse object in new work.

Code Samples

The following code sample, when placed in StarterPlayerScripts will create a tool in the player's backpack that, once equipped, will change the BasePart.BrickColor of every BasePart the player clicks on.

Color Randomizer Tool


local Players = game:GetService("Players")

local localPlayer = Players.LocalPlayer
local backpack = localPlayer:WaitForChild("Backpack")

local tool = Instance.new("Tool")
tool.RequiresHandle = false
tool.CanBeDropped = false
tool.Parent = backpack

tool.Equipped:Connect(function(mouse)
    mouse.Button1Down:Connect(function()
        if mouse.Target and mouse.Target.Parent then
            mouse.Target.BrickColor = BrickColor.random()
        end
    end)
end)

Button1Up

Fires when the left mouse button is released.

For information on how to obtain the Mouse object, please see the Mouse page.

Developers can find out the position of the mouse in world-space, and if it is pointing at any BasePart using the Mouse.Hit and Mouse.Target properties.

Note, developers are recommended to use UserInputService instead of the Mouse object in new work.

Code Samples

The follow example changes the BasePart.BrickColor of every BasePart the player clicks and releases their mouse on.

In order for a part to change color, the player's mouse must be over the part both when the player presses their left mouse button down and when the player releases their left mouse button.

Color Randomizer Tool (Button1Up)


local Players = game:GetService("Players")

local player = Players.LocalPlayer

local mouse = player:GetMouse()
local target = nil

local function button1Down()
    target = mouse.Target
end

local function button1Up()
    if target == mouse.Target then
        target.BrickColor = BrickColor.random()
    end
end

mouse.Button1Down:Connect(button1Down)
mouse.Button1Up:Connect(button1Up)

Button2Down

The Button2Down even fires when the player presses their right mouse button.

This can also be accessed from a Tool. For example, when placed in a LocalScript, the code below prints Button2Down whenever the right mouse button is pressed:


local Tool = script.Parent --make sure this is a Tool object

Tool.Equipped:Connect(function(Mouse)
    Mouse.Button2Down:Connect(function()
        print("Button2Down")
    end)
end).

Developers can find out the position of the mouse in world-space, and if it is pointing at any BasePart, using the Mouse.Hit and Mouse.Target properties.

For information on how to obtain the mouse object, please see the Mouse page.

Note, developers are recommended to use UserInputService instead of the Mouse object in new work.

Code Samples

The following code sample, when placed in StarterPlayerScripts will create a tool in the player's backpack that, once equipped, will change the BasePart.BrickColor of every BasePart the player clicks on.

Color Randomizer Tool


local Players = game:GetService("Players")

local localPlayer = Players.LocalPlayer

local backpack = localPlayer:WaitForChild("Backpack")

local tool = Instance.new("Tool")
tool.RequiresHandle = false
tool.CanBeDropped = false
tool.Parent = backpack

tool.Equipped:Connect(function(mouse)
    mouse.Button2Down:Connect(function()
        if mouse.Target and mouse.Target.Parent then
            mouse.Target.BrickColor = BrickColor.random()
        end
    end)
end)

Button2Up

Fired when the right mouse button is released.


mouse.Button2Up:Connect(function()
print("button 2 up!")
end

For information on how to obtain the Mouse object, please see the Mouse page.

Developers can find out the position of the mouse in world-space, and if it is pointing at any BasePart using the Mouse.Hit and Mouse.Target properties.

Note, developers are recommended to use UserInputService instead of the Mouse object in new work.

Code Samples

The follow example changes the BasePart.BrickColor of every BasePart the player clicks and releases their right mouse button on.

In order for a part to change color, the player's mouse must be over the part both when the player presses their right mouse button down and when the player releases their right mouse button.

Color Randomizer Tool (Button2Up)


local Players = game:GetService("Players")

local mouse = Players.LocalPlayer:GetMouse()
local target = nil

mouse.Button2Down:Connect(function()
    target = mouse.Target
end)

mouse.Button2Up:Connect(function()
    if target == mouse.Target then
        target.BrickColor = BrickColor.random()
    end
end)

Idle

Fired during every heartbeat that the mouse isn't being passed to another mouse event.

Note, this event should not be used to determine when the mouse is still. As it fires every heartbeat it will fire between Mouse.Move events.

For information on how to obtain the Mouse object, please see the Mouse page.

Developers can find out the position of the mouse in world-space, and if it is pointing at any BasePart using the Mouse.Hit and Mouse.Target properties.

Note, developers are recommended to use UserInputService instead of the Mouse object in new work.

Code Samples

This example demonstrates how mouse events are passed during each frame

Mouse.Idle


local Players = game:GetService("Players")
local RunService = game:GetService("RunService")

local player = Players.LocalPlayer

local mouse = player:GetMouse()

local events = {
    "Button1Down",
    "Button1Up",
    "Button2Down",
    "Button2Up",
    "Idle",
    "Move",
    "WheelBackward",
    "WheelForward",
    "KeyDown",
    "KeyUp",
}

local currentEvent
local frame = 0

local function processInput()
    frame = frame + 1
    print("Frame", frame, "- mouse event was passed to", currentEvent)
end

for _, event in pairs(events) do
    mouse[event]:Connect(function()
        currentEvent = event
    end)
end

RunService:BindToRenderStep("ProcessInput", Enum.RenderPriority.Input.Value, processInput)

Move

Fired when the mouse is moved.

Note, this event is fired when the mouse's position is updated, therefore it will fire repeatedly while being moved.

For information on how to obtain the Mouse object, please see the Mouse page.

Developers can find out the position of the mouse in world-space, and if it is pointing at any BasePart using the Mouse.Hit and Mouse.Target properties.


mouse.Move:Connect(function()
    local position = mouse.Hit.p
    local target = mouse.Target
    print(target, position)
end)

Note, developers are recommended to use UserInputService instead of the Mouse object in new work.

Code Samples

The example below allows the local player to move parts with their mouse.

When the player presses their left mouse button over a part, that part is the mouse's target and becomes the point. Until the player releases their left mouse button, that part will move to the mouse's world position when the player moves their mouse.

Note that the Mouse.TargetFilter property allows the code to ignore the part being moved when determining the mouse's world position.

The code should work as expected when placed in a LocalScript.

Move Parts with the Mouse


local Players = game:GetService("Players")

local player = Players.LocalPlayer

local mouse = player:GetMouse()

local point
local down

local function selectPart()
    if mouse.Target and not mouse.Target.Locked then
        point = mouse.Target
        mouse.TargetFilter = point
        down = true
    end
end

local function movePart()
    if down and point then
        local posX, posY, posZ = mouse.Hit.X, mouse.Hit.Y, mouse.Hit.Z
        point.Position = Vector3.new(posX, posY, posZ)
    end
end

local function deselectPart()
    down = false
    point = nil
    mouse.TargetFilter = nil
end

mouse.Button1Down:Connect(selectPart)
mouse.Button1Up:Connect(deselectPart)
mouse.Move:Connect(movePart)

WheelBackward

The WheelBackward event fires when the mouse wheel is scrolled backwards. Possible uses for this event include toggling a gun's scope in a first person shooter (FPS) or zooming the player's camera.

This can be used alongside the scrolling forward event, Mouse.WheelForward.

For information on how to obtain the Mouse object, please see the Mouse page.

Note, developers are recommended to use UserInputService instead of the Mouse object in new work.

Code Samples

The below example assumes that you have already got the player's mouse (and set it as a variable named 'mouse'), whether by use of a Tool, HopperBin or the Player:GetMouse() method. It will print "Wheel went backwards!" when the player scrolls backwards.

Mouse.WheelBackward


local Players = game:GetService("Players")

local player = Players.LocalPlayer

local mouse = player:GetMouse()

local function onWheelBackward()
    print("Wheel went backwards!")
end

mouse.WheelBackward:Connect(onWheelBackward)

WheelForward

The WheelForward event fires when the mouse wheel is scrolled forwards. Possible uses for this event include toggling a gun's scope in a first person shooter (FPS) or zooming the player's camera.

This can be used alongside the scrolling backward event, Mouse.WheelBackward.

For information on how to obtain the Mouse object, please see the Mouse page.

Note, developers are recommended to use UserInputService instead of the Mouse object in new work.

Code Samples

The below example assumes that you have already got the player's mouse (and set it as a variable named 'mouse'), whether by use of a Tool, HopperBin or the Player:GetMouse() method. It will print "Wheel went forward!" when the player scrolls forwards.

Mouse.WheelForward


local Players = game:GetService("Players")

local player = Players.LocalPlayer

local mouse = player:GetMouse()

local function onWheelBackward()
    print("Wheel went forward!")
end

mouse.WheelForward:Connect(onWheelBackward)

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:

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.

A cropped screenshot of the Explorer window. A Model contains ModelA and ModelB, which each contain a Part, PartA and PartB respectively. PartA contains a Fire object named FireA.

  • 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:

    1. On Model with ModelA, PartA then FireA.

    2. On ModelA, with PartA then FireA.

    3. 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