Instance

Show Deprecated
Not Creatable
Not Browsable

Instance is the base class for all classes in the Roblox class hierarchy. Every other class that the Roblox engine defines inherits all of the members of Instance. It is not possible to directly create Instance objects.

Instance has a special function called Instance.new() which is used to create objects via code. This function takes the name of the class as a parameter and returns the created object. Abstract classes and services cannot be created with the Instance.new function.

Summary

Properties

Determines if an Instance can be cloned using Instance:Clone() or saved to file.

A read-only string representing the class this Instance belongs to.

READ ONLY
NOT REPLICATED

A non-unique identifier of the Instance.

Determines the hierarchical parent of the Instance.

NOT REPLICATED

A deprecated property that used to protect CoreGui objects.

HIDDEN
HIDDEN
NOT REPLICATED

Events


Fires when the Instance.Parent property of the object or one of its ancestors is changed.


Fires whenever an attribute is changed on the Instance.


Fired immediately after a property of an object changes.


Fires after an object is parented to this Instance.


Fires after a child is removed from this Instance.


Fires after a descendant is added to the Instance.


Fires immediately before a descendant of the Instance is removed.


Fires immediately before the instance is destroyed via Instance:Destroy().

Methods

ClearAllChildren(): void  

This function destroys all of an Instance's children.


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.


Returns the first ancestor of the Instance whose Instance.Name is equal to the given name.


Returns the first ancestor of the Instance whose Instance.ClassName is equal to the given className.


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.


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.


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


Returns the Actor associated with the Instance, if any.

GetAttribute(attribute: string): Variant  

Returns the attribute which has been assigned to the given name.


Returns an event that fires when the given attribute changes.


Returns a dictionary of string → variant pairs for each of the Instance's attributes.


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.


Returns a string describing the Instance's ancestry.


Get an event that fires when a given property of an object changes.

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.


Returns true if an Instance is a descendant of the given ancestor.

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.

Properties

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.


1local part = Instance.new("Part")
2print(part:Clone()) --> Part
3part.Archivable = false
4print(part:Clone()) --> nil
5

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:


1for _, child in ipairs(game.Workspace:GetChildren()) do
2 if child.ClassName == "Part" then
3 print("Found a Part")
4 -- will find Parts in model, but NOT TrussParts, WedgeParts, etc
5 end
6end
7

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:


1local baseplate = workspace.Baseplate
2local baseplate = workspace["Baseplate"]
3local baseplate = workspace:FindFirstChild("BasePlate")
4

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


1-- Create a part and parent it to the workspace
2local part = Instance.new("Part")
3part.Parent = workspace
4-- Instance new can also take Parent as a second parameter
5Instance.new("NumberValue", workspace)
6

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.


1local part = Instance.new("Part") -- Avoid using the second parameter here
2part.Anchored = true
3part.BrickColor = BrickColor.new("Really red")
4-- Potentially many other property changes could go here here...
5-- Always set parent last!
6part.Parent = workspace
7

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

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.

SourceAssetId

Hidden
Not Replicated

Events

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.

If you need to detect when an instance is destroyed via Instance:Destroy(), consider the Instance.Destroying event instead. This event fires when an object is deleted in Studio with nil as the parent argument.

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

Instance.AncestryChanged

1local part = Instance.new("Part")
2part.Parent = workspace
3
4local function onAncestryChanged(child, parent)
5 print(child.Name .. " is now a child of " .. parent.Name)
6end
7
8part.AncestryChanged:Connect(onAncestryChanged)
9
10part.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:


1local function attributeChanged(attributeName)
2 print(attributeName, "changed")
3end
4
5instance.AttributeChanged:Connect(attributeChanged)
6

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

Change Detector

1local object = script.Parent
2
3local function onChanged(property)
4 -- Get the current value of the property
5 local value = object[property]
6 -- Print a message saying what changed
7 print(object:GetFullName() .. "." .. property .. " (" .. typeof(value) .. ") changed to " .. tostring(value))
8end
9
10object.Changed:Connect(onChanged)
11-- Trigger a simple change in the object (add an underscore to the name)
12object.Name = "_" .. object.Name
Changed Event

1-- Demonstrate the Changed event by creating a Part
2local part = Instance.new("Part")
3part.Changed:Connect(print)
4-- This fires Changed with "Transparency"
5part.Transparency = 0.5
6-- Similarly, this fires Changed with "Number"
7part.Name = "SomePart"
8-- Since changing BrickColor will also change other
9-- properties at the same time, this line fires Changed
10-- with "BrickColor", "Color3" and "Color3uint16".
11part.BrickColor = BrickColor.Red()
12
13-- A NumberValue holds a double-precision floating-point number
14local vNumber = Instance.new("NumberValue")
15vNumber.Changed:Connect(print)
16-- This fires Changed with 123.456 (not "Value")
17vNumber.Value = 123.456
18-- This does not fire Changed
19vNumber.Name = "SomeNumber"
20
21-- A StringValue stores one string
22local vString = Instance.new("StringValue")
23vString.Changed:Connect(print)
24-- This fires Changed with "Hello" (not "Value")
25vString.Value = "Hello"

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:


1workspace.ChildAdded:Connect(function(child)
2 -- need to use WaitForChild as descendants may not have replicated yet
3 local head = child:WaitForChild("Head")
4end)
5

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

Instance.ChildAdded

1local function onChildAdded(instance)
2 print(instance.Name .. " added to the workspace")
3end
4
5workspace.ChildAdded:Connect(onChildAdded)
6
7local part = Instance.new("Part")
8part.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.DescendantRemoved.

See also Instance.ChildAdded.

Parameters

child: Instance

The Instance that has been removed.


Code Samples

Instance.ChildRemoved

1local function onChildRemoved(instance)
2 print(instance.Name .. " removed from the workspace")
3end
4
5workspace.ChildRemoved:Connect(onChildRemoved)
6
7local part = Instance.new("Part")
8part.Parent = workspace
9
10task.wait(2)
11
12part: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

Instance.DescendantAdded

1local function onDescendantAdded(descendant)
2 print(descendant)
3end
4
5workspace.DescendantAdded:Connect(onDescendantAdded)
6
7local part = Instance.new("Part")
8part.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 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:


1workspace.DescendantRemoving:Connect(function(descendant)
2 -- Don't manipulate the parent of descendant in this function!
3 -- This event fires BECAUSE the parent of descendant was manipulated,
4 -- and the change hasn't happened yet, i.e. this function fires before that happens.
5 -- Therefore, it is problematic to change the parent like this:
6 descendant.Parent = game
7end)
8local part = Instance.new("Part")
9part.Parent = workspace
10part.Parent = nil -- This triggers DescendantRemoving on Workspace:
11--> Something unexpectedly tried to set the parent of Part to NULL while trying to set the parent of Part. Current parent is Workspace.
12

See also DescendantAdded.

Parameters

descendant: Instance

The Instance that is being removed.


Code Samples

Instance.DescendantRemoving

1workspace.DescendantRemoving:Connect(function(descendant)
2 print(descendant.Name .. " is currently parented to " .. tostring(descendant.Parent))
3end)
4local part = Instance.new("Part")
5part.Parent = workspace
6part.Parent = nil
7--> Part is currently parented to Workspace
8print(part.Parent)
9--> nil

Destroying

The Destroying event fires immediately before the Instance or one of its ancestors is destroyed.

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.

This event doesn't fire when an Instance is deleted in Studio. To detect this, use Instance.AncestryChanged.


Code Samples

Using the Destroying Event

1local part = Instance.new("Part", workspace)
2
3local function onPartDestroying()
4 print("Before yielding:", part:GetFullName(), #part:GetChildren())
5 task.wait()
6 print("After yielding:", part:GetFullName(), #part:GetChildren())
7end
8
9part.Destroying:Connect(onPartDestroying)
10
11part:Destroy()

Methods

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.


1for _, instance in pairs(object:GetDescendants()) do
2 if instance:IsA("BasePart") then
3 instance:Destroy()
4 end
5end
6

Returns

void

Code Samples

Instance:ClearAllChildren

1local part = Instance.new("Part")
2
3-- add some sparkles
4for _ = 1, 3 do
5 local sparkles = Instance.new("Sparkles")
6 sparkles.Parent = part
7end
8
9print("Part has", #part:GetChildren(), "children")
10--> Part has 3 children
11
12part:ClearAllChildren()
13
14print("Part has", #part:GetChildren(), "children")
15--> Part has 0 children

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

Clone Example

1-- Get a reference to an existing object
2local original = workspace.Model
3-- Create the model copy
4local copy = original:Clone()
5-- Parent the copy to the same parent as the original
6copy.Parent = original.Parent
7-- Move the copy so it's not overlapping the original
8copy: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.


1local part = Instance.new("Part")
2part.Name = "Hello, world"
3part:Destroy()
4-- Don't do this:
5print(part.Name) --> "Hello, world"
6-- Do this to prevent the above line from working:
7part = nil
8

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:


1object.Parent = nil
2wait(2)
3object.Parent = workspace
4

To Destroy an object after a set amount of time, use Debris:AddItem().


Returns

void

Code Samples

Instance:Destroy

1local Part = workspace.Part
2
3Part:Destroy()
4
5Part.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'.


1local car = object:FindFirstAncestor("Car")
2

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:


1local model = part:FindFirstAncestorOfClass("Model")
2

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:


1print(part:IsA("Part")) --> true
2print(part:IsA("BasePart")) --> true
3print(part:IsA("Instance")) --> true
4

Therefore, the following code sample will return the first BasePart ancestor, regardless of if it is a WedgePart, MeshPart or Part.


1local part = object:FindFirstAncestorWhichIsA("BasePart")
2

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 found with the given name. If no child exists with the given name, 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. Use this function if your code cannot guarantee the existence of an object with a given name.

Checking the Existence of An Object

FindFirstChild is necessary if you need to verify an object something exists before continuing. Attempting to index a child by name using the dot operator throws an error if the child doesn't exist.


1-- The following line errors if Part doesn't exist in the Workspace:
2workspace.Part.Transparency = 0.5
3

Use FindFirstChild to first check for Part, then use an if-statement to run code that needs it.


1local part = workspace:FindFirstChild("Part")
2if part then
3 part.Transparency = 0.5
4end
5

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.


1local part = Instance.new("Part")
2local folder = Instance.new("Folder")
3folder.Name = "Color"
4folder.Parent = part
5local c = part.Color --> A Color3
6local c2 = part:FindFirstChild("Color") --> The Folder
7

A benefit of using FindFirstChild in this way is that the introduction of new properties does not impose a risk on your code.

Tip: If you only need to use the result of a FindFirstChild call once, such as getting the property of a child if it exists, you can use the following syntax with the and operator:


1local myColor = workspace:FindFirstChild("SomePart") and workspace.SomePart.Color
2

If SomePart exists, myColor will contain the Color of SomePart. Otherwise, it'll be nil without throwing an error. This works due to short-circuiting: Lua ignores the right side if the left is nil/false

Performance Note

FindFirstChild takes about 20% longer than using dot operator, and almost 8 times longer than simply storing a reference to an object. Therefore, you should avoid calling FindFirstChild in performance dependent code, such as in tight loops or functions connected to RunService.Heartbeat/RunService.RenderStepped. 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

Instance:FindFirstChild

1local found = workspace:FindFirstChild("Brick")
2
3if found then
4 found.Name = "Foo"
5end

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

1local Players = game:GetService("Players")
2
3local player = Players.LocalPlayer
4local character = player.Character or player.CharacterAdded:Wait()
5
6local humanoid
7
8while not humanoid do
9 humanoid = character:FindFirstChildOfClass("Humanoid")
10 if not humanoid then
11 character.ChildAdded:Wait()
12 end
13end

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:


1print(part:IsA("Part")) --> true
2print(part:IsA("BasePart")) --> true
3print(part:IsA("Instance")) --> true
4

Therefore, the following code sample will return the first BasePart child, regardless of if it is a WedgePart, MeshPart or Part.


1local part = object:FindFirstChildWhichIsA("BasePart")
2

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

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:


1local initialPosition = instance:GetAttribute("InitialPosition")
2

See also:

Parameters

attribute: string

The name of the attribute being retrieved.


Returns

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:


1local function attributeChanged()
2 print("Attribute changed")
3end
4
5instance:GetAttributeChangedSignal("InitialPosition"):Connect(attributeChanged)
6

See also:

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:


1local attributes = instance:GetAttributes()
2for name, value in pairs(attributes) do
3 print(name .. " " .. value)
4end
5

See also:


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:


1-- Numeric for-loop example
2local children = workspace:GetChildren()
3for i = 1, #children do
4 local child = children[i]
5 print(child.Name .. " is child number " .. i)
6end
7

1-- Generic for-loop example
2local children = workspace:GetChildren()
3for i, child in ipairs(children) do
4 print(child.Name .. " is child number " .. i)
5end
6

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

Instance:GetChildren

1local children = workspace:GetChildren()
2
3for i = 1, #children do
4 print(i, children[i].Name)
5end

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

1print(workspace:GetDebugId()) --> 39FA_12
2print(workspace:GetDebugId(10)) --> 39FA2FEF4D_12
3print(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:

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.


1local descendants = game.Workspace.Model:GetDescendants()
2
3-- Loop through all of the descendants of the model and
4-- print out their name
5for index, descendant in pairs(descendants) do
6 print(descendant.Name)
7end
8
9-- Prints:
10-- C
11-- D
12-- E
13-- InnerModel
14-- A
15-- B
16

Returns

An array containing the Instance's descendants.

Code Samples

Instance:GetDescendants

1local descendants = workspace:GetDescendants()
2
3-- Loop through all of the descendants of the Workspace. If a
4-- BasePart is found, the code changes that parts color to green
5for _, descendant in pairs(descendants) do
6 if descendant:IsA("BasePart") then
7 descendant.BrickColor = BrickColor.Green()
8 end
9end

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

Instance:GetFullName

1-- Create a simple hierarchy
2local model = Instance.new("Model")
3local part = Instance.new("Part")
4part.Parent = model
5local fire = Instance.new("Fire")
6fire.Parent = part
7
8print(fire:GetFullName()) --> Model.Part.Fire
9
10model.Parent = workspace
11
12print(fire:GetFullName()) --> Workspace.Model.Part.Fire
13
14part.Name = "Hello, world"
15
16print(fire:GetFullName()) --> Workspace.Model.Hello, world.Fire
Instance:GetFullName Lua Implementation

1local function getFullName(object)
2 local result = object.Name
3 object = object.Parent
4 while object and object ~= game do
5 -- Prepend parent name
6 result = object.Name .. "." .. result
7 -- Go up the hierarchy
8 object = object.Parent
9 end
10 return result
11end
12
13print(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

Changed and GetPropertyChangedSignal

1local part = Instance.new("Part")
2
3local function onBrickColorChanged()
4 print("My color is now " .. part.BrickColor.Name)
5end
6
7local function onChanged(property)
8 if property == "BrickColor" then
9 onBrickColorChanged()
10 end
11end
12
13part:GetPropertyChangedSignal("BrickColor"):Connect(onBrickColorChanged)
14part.Changed:Connect(onChanged)
15
16-- Trigger some changes (because we connected twice,
17-- both of these will cause two calls to onBrickColorChanged)
18part.BrickColor = BrickColor.new("Really red")
19part.BrickColor = BrickColor.new("Institutional white")
Old-to-New Values with Changed

1local part = Instance.new("Part")
2
3local currentColor = part.BrickColor
4
5local function onBrickColorChanged()
6 local newColor = part.BrickColor
7 print("Color changed from", currentColor.Name, "to", newColor.Name)
8 currentColor = newColor
9end
10part:GetPropertyChangedSignal("BrickColor"):Connect(onBrickColorChanged)
11
12part.BrickColor = BrickColor.new("Really red")
13part.BrickColor = BrickColor.new("Really blue")
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:


1local function paintFigure(character, color)
2 -- Iterate over the child objects of the character
3 for _, child in pairs(character:GetChildren()) do
4 -- Filter out non-part objects, such as Shirt, Pants and Humanoid
5 -- R15 use MeshPart and R6 use Part, so we use BasePart here to detect both:
6 if child:IsA("BasePart") then
7 child.BrickColor = color
8 end
9 end
10end
11paintFigure(game.Players.Player.Character, BrickColor.new("Bright blue"))
12

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

Instance:IsA

1print(workspace:IsA("Instance")) --> true
2print(workspace:IsA("Workspace")) --> true
3print(game:IsA("workspace")) --> false
4print(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

1print(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

1local part = Instance.new("Part")
2print(part:IsDescendantOf(game))
3--> false
4
5part.Parent = workspace
6print(part:IsDescendantOf(game))
7--> true
8
9part.Parent = game
10print(part:IsDescendantOf(game))
11--> true

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:


1instance:SetAttribute("InitialPosition", Vector3.new(0, 0, 0))
2

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

No return.

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 function will return nil and time out after timeOut seconds elapsing without the child being found.

Where should WaitForChild be used?

WaitForChild is extremely important when working on code ran by the client (in a LocalScript). Roblox does not guarantee the time or order in which objects are replicated from the server to the client. This can cause scripts to break when indexing objects that do not exist yet.

For example, a LocalScript may access a Model in the Workspace called 'Ship' like so:


1local ship = workspace.Ship
2-- Will error if ship hasn't replicated
3

However if the model 'Ship' has not replicated to the client when this code is ran an error will be returned breaking the LocalScript.

Another alternative is using Instance:FindFirstChild(). Not only is this good practice when indexing objects in the DataModel (as it avoids accidentally accessing properties) but it does not break if the object does not exist. For example:


1local ship = workspace:FindFirstChild("Ship")
2-- Won't error, but ship will be nil if the ship hasn't replicated
3

Here, if the model doesn't exist the code will not error. Instead the value ship will be equal to nil. This is better, but still not much good if we want to use the ship model.

Instead WaitForChild should be used:


1local ship = workspace:WaitForChild("Ship")
2-- Will wait until the ship has replicated before continuing
3

Here, the thread will be yielded until the ship model has been found. This means the ship model can be used as soon as it is ready.

Note:

  • If a call to this function 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 form Infinite yield possible on 'X:WaitForChild("Y")', where X is the parent name and Y is the child object name.
  • This function does not yield if a child with the given name exists when the call is made.
  • This function is less efficient than Instance:FindFirstChild() or the dot operator. Therefore, it should only be used when the developer is not sure if the object has replicated to the client. Generally this is only the first time the object is accessed

Parameters

childName: string

The Instance.Name to be looked for.

timeOut: number

An optional time out parameter.


Returns

The Instance found.

Code Samples

Instance:WaitForChild

1local part = workspace:WaitForChild("Part")
2print(part.Name .. " has been added to the Workspace")