Class
Instance
Instance is the base class for all classes in the Roblox class hierarchy
which can be part of the DataModel tree.
About Instance
Instance is the base class for all classes in the Roblox class hierarchy
which can be part of the DataModel tree.
It is not possible to directly create root Instance objects, but the special
Instance.new constructor creates objects via code, taking the
name of the class as a parameter and returning the created object.
Properties 7
Archivable
: booleanDetermines if anInstanceand its descendants can be cloned usingInstance.Clone, and can be saved/published.This property determines whether the instance should be included when the experience is published or saved, or when
Clone()is called on one of the instance's ancestors. CallingClone()directly on an instance will returnnilif that instance is notArchivable.Copying an object in Studio using the Duplicate or Copy/Paste options will ignore its own
Archivableproperty and setArchivabletotruefor the copy.Capabilities
: SecurityCapabilitiesThe set of capabilities allowed to be used for scripts inside this container.The set of capabilities allowed to be used for scripts inside this instance. For the capabilities to take effect,
Instance.Sandboxedproperty must be enabled.This property is used by an experimental feature. See script capabilities for further details.
IsInSandbox
: booleanReadOnlyNotReplicatedNotScriptableIndicates whether the instance is inside a sandboxed container.This read-only property returns
trueif the instance is contained within a sandboxed container — that is, if the instance itself or any of its ancestors hasInstance.Sandboxedenabled. Otherwise it returnsfalse.This property is not scriptable and is only visible in Studio's Properties window. See script capabilities for further details.
Name
: stringA non-unique identifier of theInstance.A non-unique identifier of the
Instance. Names are used to keep the object hierarchy organized, along with allowing scripts to access specific objects. The name of an instance cannot exceed 100 characters in size.The name of an object is often used to access the object through the data model hierarchy using the following methods:
local Workspace = game:GetService("Workspace") local baseplate = Workspace.Baseplate local baseplate = Workspace["Baseplate"] local baseplate = Workspace:FindFirstChild("BasePlate")In order to make an object accessible using the dot operator (
.), its name must start with an underscore or letter, and the rest of the name can only contain letters, numbers, or underscores (no other special characters). If an object's name does not follow this syntax, it will not be accessible using the dot operator and Luau will not interpret its name as an identifier.If more than one object with the same name are siblings, any attempt to index an object by that name will return only one of the objects, similar to
Instance.FindFirstChild, but not always the desired object. If a specific object needs to be accessed through code, it's recommended to give it a unique name or guarantee that none of its siblings share the same name.See also
Instance.GetFullNameto obtain a full name including the object's hierarchy.Parent
: InstanceNotReplicatedDetermines the hierarchical parent of theInstance.The
Parentproperty determines the hierarchical parent of theInstance. The following terminology is commonly used when talking about how this property is set:An object is a child of, or is parented to, another object when its
Parentis set to that object.The descendants of an
Instanceare the children of that object, plus the descendants of the children as well.The ancestors of an
Instanceare all the objects that the instance is a descendant of.
It is from the
Parentproperty that many other API members get their name, such asGetChildren()andFindFirstChild(). This property is also used to manage whether an object exists in the experience or needs to be removed. As long as an object's parent is in theDataModel, is stored in a variable, or is referenced by another object's property, the object remains in the experience; otherwise, the object will automatically be removed.Calling
Destroy()will set theParentof anInstanceand all of its descendants tonil, and also lock theParentproperty. An error is raised when setting theParentof a destroyed object.Newly created objects using
Instance.newwill not have a parent, and usually will not be visible or function until one is set.Object Replication
An object created by the server will not replicate to clients until it is parented to some object that is replicated. When creating an object and setting many properties, it's recommended to set the
Parentproperty last. This ensures the object replicates once, instead of replicating many property changes.local Workspace = game:GetService("Workspace") -- Set new instance's parent last (recommended) local part = Instance.new("Part") part.Position = Vector3.new(0, 10, 0) part.Parent = WorkspaceHowever, if parenting parts to a
Modelwhose parent hasn't been set yet, parenting each part to that model is acceptable since the model would not have replicated.PredictionMode
: PredictionModeReadOnlyNotReplicatedNotScriptableReflects the client-side prediction mode applied to the instance under server-authoritative physics.This property reflects the
PredictionModecurrently applied to the instance, which determines whether the instance's state is predicted on the client ahead of the authoritative server state under server-authoritative physics. It defaults toAutomatic.This property is read-only and cannot be assigned directly from a script; the prediction mode is set through
RunService.SetPredictionMode. The property is shown in Studio's Properties window only when the experience uses server-authoritative physics.Automatic(default) — the engine automatically decides whether to predict the instance. Currently, onlyBasePartsnear the local player character'sHumanoidare predicted, within a dynamic radius that grows and shrinks based on the device's capacity to handle the simulation load.On— the instance is always predicted. If it is aBasePart, its physics properties are predicted ahead of the replicated authoritative server state, and mismatches in the instance's attributes between the client and server cause a rollback and resimulation.Off— the instance is not predicted, and regular network ownership semantics apply.
Sandboxed
: booleanNotReplicatedWhen enabled, the instance can only access abilities in itsCapabilitieslist.Turns the instance to be a sandboxed container, an experimental feature which limits the actions that scripts inside a particular container can perform. See script capabilities for further details.
Methods 31
AddTag
(tag: string) → ()Applies a tag to the instance.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.GetInstanceAddedSignalwith the given tag.Warnings
An instance's tags that were added client-side will be dropped if the server later adds or removes a tag on that instance because the server replicates all tags together and overwrites previous tags.
When tagging an instance, it is 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 callingInstance.RemoveTag, callingInstance.Destroy, or in a function connected to a signal returned byCollectionService.GetInstanceRemovedSignal.
ClearAllChildren
() → ()This method destroys all of an instance's children.This method destroys all of an instance's children and descendants.
local part = Instance.new("Part") -- Add some sparkles for i = 1, 3 do local sparkles = Instance.new("Sparkles") sparkles.Parent = part local sc = Instance.new("Sparkles") sc.Parent = sparkles end print("Children:", #part:GetChildren()) --> Children: 3 part:ClearAllChildren() print("Children:", #part:GetChildren()) --> Children: 0If you do not wish to destroy all children and descendants, use either
Instance.GetChildrenorInstance.GetDescendantsto loop through those children/descendants and select what to destroy. For example, the following code sample will destroy allBasePartsdescending from aModel:local Workspace = game:GetService("Workspace") local model = Workspace:FindFirstChild("TestModel") for _, descendant in model:GetDescendants() do if descendant:IsA("BasePart") then descendant:Destroy() end endClone
() → InstanceCreate a copy of an instance and all its descendants, ignoring instances that are notArchivable.Clone()creates a copy of an instance and all of its descendants, ignoring all instances that are notArchivable. The copy of the root instance is returned by this method and itsParentis set tonil. Note that if the instance itself hasArchivableset tofalse, this method will returnnil.If a reference property such as
ObjectValue.Valueis set in a cloned instance, the value of the copy's property depends on the original's value:- If a reference property refers to an instance that was also cloned, the copy will refer to the copy.
- If a reference property refers to an instance that was not cloned, the same value is maintained in the copy.
Destroy
() → ()Sets theInstance.Parentproperty tonil, locks theInstance.Parentproperty, disconnects all connections, and callsDestroy()on all children.Sets the
Instance.Parentproperty tonil, locks theInstance.Parentproperty, disconnects all connections, and callsDestroy()on all children. This method 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 which can lead to serious performance issues over time.
As a best practice after calling
Destroy()on an object, set any variables referencing the object (or its descendants) tonil. 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 = nilOnce an
Instancehas been destroyed by this method, it cannot be reused because theInstance.Parentproperty is locked. To temporarily remove an object instead of destroying it, setParenttonil. For example:local Workspace = game:GetService("Workspace") object.Parent = nil task.wait(2) object.Parent = WorkspaceTo destroy an object after a set amount of time, use
Debris.AddItem.FindFirstAncestor
(name: string) → Instance?Returns the first ancestor of theInstancewhoseInstance.Nameis equal to the given name.Returns the first ancestor of the
InstancewhoseInstance.Nameis equal to the given name.This method works upwards, meaning it starts at the instance's immediate
Instance.Parentand works up towards theDataModel. If no matching ancestor is found, it returnsnil.The following code snippet would find the first ancestor of the object named
Car.local car = object:FindFirstAncestor("Car")For variants of this method that find ancestors of a specific class, please see
Instance.FindFirstAncestorOfClassandInstance.FindFirstAncestorWhichIsA.FindFirstAncestorOfClass
(className: string) → Instance?Returns the first ancestor of theInstancewhoseObject.ClassNameis equal to the given className.Returns the first ancestor of the
InstancewhoseObject.ClassNameis equal to the given className.This method works upwards, meaning it starts at the instance's immediate
Instance.Parentand works up towards theDataModel. If no matching ancestor is found, it returnsnil.A common use of this method is finding the
ModelaBasePartbelongs to. For example:local model = part:FindFirstAncestorOfClass("Model")This method is a variant of
Instance.FindFirstAncestorwhich checks theObject.ClassNameproperty rather thanInstance.Name.Instance.FindFirstAncestorWhichIsAalso exists, using theObject.IsAmethod instead to respect class inheritance.FindFirstAncestorWhichIsA
(className: string) → Instance?Returns the first ancestor of theInstancefor whomObject.IsAreturns true for the given className.Returns the first ancestor of the
Instancefor whomObject.IsAreturns true for the given className.This method works upwards, meaning it starts at the instance's immediate
Instance.Parentand works up towards theDataModel. If no matching ancestor is found, it returnsnil.Unlike
Instance.FindFirstAncestorOfClass, this method usesObject.IsAwhich respects class inheritance. For example:print(part:IsA("Part")) --> true print(part:IsA("BasePart")) --> true print(part:IsA("Instance")) --> trueTherefore, the following code sample will return the first
BasePartancestor, regardless of if it is aWedgePart,MeshPartorPart.local part = object:FindFirstAncestorWhichIsA("BasePart")See also
Instance.FindFirstAncestor.FindFirstChild
(name: string, recursive: boolean = false) → Instance?Returns the first child of theInstancefound with the given name.Returns the first child of the
Instancewith the given name, ornilif no such child exists. If the optionalrecursiveargument istrue, this method searches all descendants rather than only the immediate children of theInstance.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.local Workspace = game:GetService("Workspace") -- The following line errors if the part doesn't exist in the workspace Workspace.Part.Transparency = 0.5A better approach is to use
FindFirstChild()to first check forPart, then use anifstatement to run code that needs it.local Workspace = game:GetService("Workspace") local part = Workspace:FindFirstChild("Part") if part then part.Transparency = 0.5 endFinding a Child Whose Name Matches a Property
Sometimes the
Nameof an object is the same as that of a property of itsParent. When using the dot operator, properties take precedence over children if they share a name.In the following example, a
FoldercalledColoris added to aPart, which also has thePart.Colorproperty. Notice thatpart.Colorrefers to theColor3property value, not the childFolderinstance. A benefit of usingFindFirstChild()is that the introduction of new properties does not impose a risk on your code.local part = Instance.new("Part") local folder = Instance.new("Folder") folder.Name = "Color" folder.Parent = part local c1 = part.Color -- The property local c2 = part:FindFirstChild("Color") -- The child folderPerformance Notes
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 toRunService.HeartbeatandRunService.PreRender. Instead, store the result in a variable, or consider usingChildAddedorWaitForChild()to detect when a child of a given name becomes available.FindFirstChildOfClass
(className: string) → Instance?Returns the first child of theInstancewhoseClassNameis equal to the given class name.Returns the first child of the
InstancewhoseClassNameis equal to the givenclassName. UnlikeInstance.FindFirstChildWhichIsA, this method only returns objects whose class matchesclassName, ignoring class inheritance. If no matching child is found, this method returnsnil.FindFirstChildWhichIsA
(className: string, recursive: boolean = false) → Instance?Returns the first child of theInstancefor whomObject.IsAreturns true for the given className.Returns the first child of the
Instancefor whomObject.IsAreturns true for the given className.If no matching child is found, this method returns
nil. If the optional recursive argument is true, this method searches all descendants rather than only the immediate children of theInstance.Unlike
Instance.FindFirstChildOfClass, this method usesObject.IsAwhich respects class inheritance. For example:print(part:IsA("Part")) --> true print(part:IsA("BasePart")) --> true print(part:IsA("Instance")) --> trueTherefore, the following code sample will return the first
BasePartchild, regardless of if it is aWedgePart,MeshPartorPart.local part = object:FindFirstChildWhichIsA("BasePart")Developers looking for a child by name, should use
Instance.FindFirstChildinstead.FindFirstDescendant
(name: string) → Instance?Returns the first descendant found with the givenInstance.Name.Returns the first descendant found with the given
Instance.Name.This method is disabled and cannot be used. To find the first descendant of an instance, consider using the
recursiveparameter onInstance.FindFirstChildinstead.GetAttribute
(attribute: string) → VariantReturns the value which has been assigned to the given attribute name.This method returns the value which has been assigned to the given attribute name. If no attribute has been assigned,
nilis returned.For example, the following code snippet sets and then gets the value of the instance's
InitialPositionattribute:local Workspace = game:GetService("Workspace") local part = Workspace.Part part:SetAttribute("InitialPosition", part.Position) local initialPosition = instance:GetAttribute("InitialPosition") print(initialPosition)See Also
Instance.SetAttributewhich sets the attribute with the given name to the given value.Instance.GetAttributeswhich returns a dictionary of key‑value pairs for each of the instance's attributes.
GetAttributeChangedSignal
(attribute: string) → RBXScriptSignalReturns an event that fires when the given attribute changes.This method returns an event that behaves exactly like the
Changedevent, except that it only fires when the specific given attribute changes; effectively it is similar toGetPropertyChangedSignal()but for attributes.It's generally a good idea to use this method instead of a connection to
Changedwith 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.The following code example returns a signal that fires the function
attributeChanged()when the part'sInitialPositionattribute changes:local Workspace = game:GetService("Workspace") local part = Workspace.Part part:SetAttribute("InitialPosition", part.Position) local function attributeChanged() print("Attribute changed") end part:GetAttributeChangedSignal("InitialPosition"):Connect(attributeChanged)See also
Instance.AttributeChangedwhich fires whenever any attribute is changed on the instance.GetAttributes
() → DictionaryReturns a dictionary of the instance's attributes.This method returns a dictionary of key‑value pairs for each attribute where the key is the attribute's name and the value is a non‑
nilvalue.For example, the following code snippet outputs an instance's attributes and values:
local Workspace = game:GetService("Workspace") local part = Workspace.Part part:SetAttribute("InitialPosition", part.Position) part:SetAttribute("CanUse", true) for name, value in part:GetAttributes() do print(name .. " = " .. value) endSee also
Instance.GetAttributewhich returns the value that has been assigned to the given attribute name.GetChildren
() → InstancesReturns an array containing all of the instance's children.Returns an array (a numerically indexed table) containing all of the instance's direct children, or every
InstancewhoseParentis equal to the object. The array can be iterated upon using either a numeric or genericforloop:local Workspace = game:GetService("Workspace") -- Numeric loop example local children = Workspace:GetChildren() for i = 1, #children do local child = children[i] print(child.Name .. " is child number " .. i) endlocal Workspace = game:GetService("Workspace") -- Generic loop example local children = Workspace:GetChildren() for i, child in children do print(child.Name .. " is child number " .. i) endNote that the returned array is not sorted in any particular order, so manual sorting (for example using
table.sort) is advised for sorting the children returned by this method.See also the
GetDescendants()method.GetDebugId
(scopeLength: int = 4) → stringPluginReturns a coded string of the debug ID used internally by Roblox.Returns a coded string of the debug ID used internally by Roblox. Note that:
- This item is protected. Attempting to use it in a
ScriptorLocalScriptwill 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).
- This item is protected. Attempting to use it in a
GetDescendants
() → InstancesReturns an array containing all of the descendants of the instance.This object method returns an array that contains all of the descendants of that object. Unlike
Instance.GetChildren, which only returns the immediate children of an object, this method finds every child of the object, every child of those children, and so on.Note that the returned array is not sorted in any particular order, so manual sorting (for example using
table.sort) is advised for sorting the descendants returned by this method. Also consdier theQueryDescendants()method to query descendants by a combination of selectors and combinators.GetFullName
() → stringReturns a string describing the instance's ancestry.Returns a string describing the instance's ancestry. The string is a concatenation of the
Nameof the object and its ancestors, separated by periods. TheDataModel(game) is not considered. For example, aPartin theWorkspacemay returnWorkspace.Part.When called on an
Instancethat is not a descendant of theDataModel, this method considers all ancestors up to and including the topmost one without aParent.This method is useful for logging and debugging. You shouldn't attempt to parse the returned string for any useful operation; this method does not escape periods (or any other symbol) in object names. In other words, although its output often appears to be a valid Luau identifier, it is not guaranteed.
GetStyled
(name: string, selector: string?) → VariantReturns the styled or explicitly modified value of the specified property, or else the default property value if it hasn't been styled/modified.This method returns the styled or explicitly modified value of the specified property, or else the default property value if it hasn't been styled/modified. This differs slightly from accessing the property value directly, such as
[GuiObject].Rotation, which returns the default or modified value of the property.GetStyledPropertyChangedSignal
(property: string) → RBXScriptSignalReturns an event that fires when the given style property changes on the instance.This method returns an event that behaves exactly like the
StyledPropertiesChangedevent, except that it only fires when the given style property changes. It's generally a good idea to use this method instead of a connection toStyledPropertiesChangedwith 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.Note that this event will not pass any arguments to a connected function, so the value of the changed property must be read directly within a script.
GetTags
() → ArrayGets an array of all tags applied to the instance.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.HasTag
(tag: string) → booleanCheck whether the instance has a given tag.This method returns
trueif the provided tag has been added to the object. You can add tags either in Studio in the Properties window or at runtime withAddTag().IsAncestorOf
(descendant: Instance) → booleanReturns true if anInstanceis an ancestor of the given descendant.Returns true if an
Instanceis an ancestor of the given descendant.An
Instanceis considered the ancestor of an object if the object'sInstance.Parentor one of it's parent'sInstance.Parentis set to theInstance.See also,
Instance.IsDescendantOf.IsDescendantOf
(ancestor: Instance) → booleanReturnstrueif anInstanceis a descendant of the given ancestor.Returns
trueif anInstanceis a descendant of the given ancestor.Note that
IsDescendantOf()cannot be used with a parameter ofnilto check if an object has been removed.See also
Instance.IsAncestorOf.IsPropertyModified
(property: string) → booleanReturnstrueif the value stored in the specified property is not equal to the code-instantiated default.This method indicates whether a specific property has been modified from the code‑instantiated default. If called on an instance newly created via code (
Instance.new), this method will returnfalse. If called on an object newly created by Studio workflows such as Explorer window insertion, the result may differ.For example, querying the
BackgroundColor3property of aTextLabelinserted via the Explorer will returntrue, but querying the same property of aTextLabelcreated throughInstance.newwill returnfalse, assuming no other changes were made to itsBackgroundColor3.Note that this method only returns useful results for services and user‑creatable instances. Return values for system‑populated properties of instances like
PackageLinkis undefined behavior.Also note that if this method returns
true, styling will not affect the property because explicitly modifying a property takes precedence over styling it. To reset a property to its code‑instantiated default and allow styling on it, useResetPropertyToDefault().QueryDescendants
(selector: string) → InstancesReturns an array containing all descendants of the instance that match theselectorstring.This object method returns an array that contains all descendants of the object that match the provided
selectorstring.selectorcan include multiple selectors and combinators to match characteristics such as the class name, instance name, and hierarchy relationships, as well as specific values of instance properties and attributes. Theselectorgrammar is similar to the one used inStyleRule, with only a few differences regarding which parts of the grammar are supported or not.Selectors
ClassName— Matches instances of the specified class in aObject.IsArelationship..Tag— Matches instances tagged with aCollectionServicetag.#Name— Matches instances of a specificInstance.Name.[property = value]— Matches instances which have the specified property and that property has the specified value. Boolean, number, and string values are supported. Letters, numbers,_, and-can be used without putting the value in quotation marks.[$attribute]— Matches instances which have the specified attribute set.[$attribute = value]— Matches instances which have the specified attribute and that attribute has the specified value. Same limitations apply as for property selectors. If you want to check for the absence of an attribute, do not query it asnil; instead use the:notpseudo‑class as in:not([$attribute]).
Selectors can also be combined. For example,
Model.Apple[$Variety = Fuji][$Flavor = 4]will match instances which are aModeltagged asAppleand which have aVarietyattribute equal toFujias well as aFlavorattribute equal to4.local Workspace = game:GetService("Workspace") -- Get all MeshPart descendants print(Workspace:QueryDescendants("MeshPart")) -- Get all descendants tagged as "Fruit" print(Workspace:QueryDescendants(".Fruit")) -- Get all descendants with the name "RedTree" print(Workspace:QueryDescendants("#RedTree")) -- Get all descendants with CanCollide property set to false print(Workspace:QueryDescendants("[CanCollide = false]")) -- Get all descendants with a "FuelCapacity" attribute assigned print(Workspace:QueryDescendants("[$FuelCapacity]")) -- Get all descendants with a "FuelCapacity" attribute set to 75 print(Workspace:QueryDescendants("[$FuelCapacity = 75]"))Combinators
Combinators let you mix basic selectors to match deeper hierarchy relationships.
>— Matches instances that are direct children of the previous filter matches.>>— Matches instances that are descendants of the previous filter matches. This is the default first filter, meaning thatSpotLight.Redis the same as>> SpotLight.Red.,— Specifies a list of multiple independent selectors for the descendant query. Only elements matching the filter are placed in the returned array;nilwill not be included for non‑matches in a query list.
local Workspace = game:GetService("Workspace") -- Get direct children of any Model that are tagged as "SwordPart" print(Workspace:QueryDescendants("Model > .SwordPart")) -- Get direct children which are a Part and are tagged as "Apple" print(Workspace:QueryDescendants("> Part.Apple")) -- Get descendants of any Model with an attribute "OnFire" set to true print(Workspace:QueryDescendants("Model >> [$OnFire = true]")) -- Get MeshPart descendants tagged as "SwordPart" OR with an attribute "OnFire" set to true print(Workspace:QueryDescendants("MeshPart.SwordPart, MeshPart[$OnFire = true]"))Pseudo-class selectors
:not(complex-selector-list)— Allows selecting instances which do not match any of the selectors inside, effectively performing a negation of the selectors. Since the expression inside is a list of complex selectors, it's possible to filter based on multiple conditions.:has(relative-selector-list)— Allows selecting instances based on which instances they contain inside. The selector list is evaluated relative to each instance.
local Workspace = game:GetService("Workspace") -- Get all descendants which are NOT of class SpotLight print(Workspace:QueryDescendants(":not(SpotLight)")) -- Get all descendants which are NOT of class SpotLight OR PointLight print(Workspace:QueryDescendants(":not(SpotLight, PointLight)")) -- Get all descendants which do NOT have an attribute "OnFire" print(Workspace:QueryDescendants(":not([$OnFire])")) -- Get all descendants EXCEPT children of a Model tagged as "SwordPart" print(Workspace:QueryDescendants(":not(Model > .SwordPart)")) -- Get descendants which contain a Tool instance as their own descendant print(Workspace:QueryDescendants(":has(Tool)")) -- Get MeshPart descendants which contain a direct child tagged as "SwordPart" print(Workspace:QueryDescendants("MeshPart:has(> .SwordPart)")) -- Get MeshPart descendants with direct children NOT of SurfaceAppearance or Texture class print(Workspace:QueryDescendants("MeshPart:has(> :not(SurfaceAppearance, Texture))"))RemoveTag
(tag: string) → ()Removes a tag from the instance.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.GetInstanceRemovedSignalwith 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.ResetPropertyToDefault
(property: string) → ()Resets a property to its default value.SetAttribute
(attribute: string, value: Variant) → ()Sets the attribute with the given name to the given value.This method sets the attribute with the given name to the given value. If the value given is
nil, the attribute will be removed, sincenilis returned by default.For example, the following code snippet sets the instance's
InitialPositionattribute toVector3.new(0, 10, 0):local Workspace = game:GetService("Workspace") local part = Workspace.Part part:SetAttribute("InitialPosition", Vector3.new(0, 10, 0))Limitations
Naming requirements and restrictions:
- Names must only use alphanumeric characters.
- You may also include periods, hyphens, slashes, and underscores.
- No spaces or unique symbols (such as @, ~, !) are allowed.
- Strings must be 100 characters or less.
- Names are not allowed to start with RBX unless the caller is a Roblox core script (reserved for Roblox).
When attempting to set an attribute to an unsupported type, an error will be thrown.
See Also
Instance.GetAttributewhich returns the value that has been assigned to the given attribute name.Instance.GetAttributeswhich returns a dictionary of key‑value pairs for each of the instance's attributes.
- Names must only use alphanumeric characters.
WaitForChild
(childName: string, timeOut: double) → InstanceReturns the child of theInstancewith the given name. If the child does not exist, it will yield the current thread until it does.Returns the child of the
Instancewith the given name. If the child does not exist, it will yield the current thread until it does. If thetimeOutparameter is specified, this method will time out after the specified number of seconds and returnnil.Primary Usage
WaitForChild()is extremely important when working on code run by the client in aLocalScript. 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 hasWorkspace.StreamingEnabledset to true,BasePartsthat 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 method does not yield if a child with the given name exists when the call is made.
Instance.FindFirstChildis a more efficient alternative toWaitForChild()for objects that are assumed to exist.- If a call to this method exceeds 5 seconds without returning, and no
timeOutparameter has been specified, a warning will be printed to the output that the thread may yield indefinitely.
Events 8
AncestryChanged
Instance.AncestryChanged:Connect(function(child, parent))Fires when theInstance.Parentproperty of this object or one of its ancestors is changed.Fires when this instance is reparented or when any of its ancestors is reparented.
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 theInstance.Destroyingevent instead.AttributeChanged
Instance.AttributeChanged:Connect(function(attribute))Fires whenever an attribute is changed on theInstance.This event fires whenever any attribute is changed on the instance, including when an attribute is set to
nil. The name of the changed attribute is passed to the connected function.For example, the following code snippet connects the
attributeChanged()function to fire whenever one of the part's attributes changes:local Workspace = game:GetService("Workspace") local part = Workspace.Part local function attributeChanged(attributeName) print(attributeName, "changed") end part.AttributeChanged:Connect(attributeChanged)See also
Instance.GetAttributeChangedSignalwhich returns an event that fires when a specific given attribute changes.ChildAdded
Instance.ChildAdded:Connect(function(child))Fires after an object is parented to thisInstance.Fires after an object is parented to this
Instance.Note, when using this method on a client to detect objects created by the server it is necessary to use
Instance.WaitForChildwhen 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:local Workspace = game:GetService("Workspace") Workspace.ChildAdded:Connect(function(child) -- Use WaitForChild() since descendants may not have replicated yet local head = child:WaitForChild("Head") end)Note, this event only operates for immediate children of the
Instance. For an event that captures all descendants, useInstance.DescendantAdded.See also
Instance.ChildRemoved.ChildRemoved
Instance.ChildRemoved:Connect(function(child))Fires after a child is removed from thisInstance.Fires after a child is removed from this
Instance.Removed refers to when an object's parent is changed from this
Instanceto something other than thisInstance. Note, this event will also fire when a child is destroyed (usingInstance.Destroy) as the destroy function sets an object's parent tonil.This event only operates for immediate children of the
Instance. For an event that captures all descendants, useInstance.DescendantRemoving.See also
Instance.ChildAdded.DescendantAdded
Instance.DescendantAdded:Connect(function(descendant))Fires after a descendant is added to theInstance.This event fires after a descendant is added to the
Instance.As it fires for every descendant, parenting an object to the
Instancewill fire the event for this object and all of its descendants individually.If you're only concerned with the direct children of the
Instance, useInstance.ChildAddedinstead.See also
Instance.DescendantRemoving.DescendantRemoving
Instance.DescendantRemoving:Connect(function(descendant))Fires immediately before a descendant of theInstanceis removed.This event fires immediately before the parent
Instancechanges such that a descendant instance will no longer be a descendant.Destroy()changes an instance'sParenttonil, so calling that method on a descendant of the parent will cause this event to fire.Since this event fires before the descendant's removal, the parent of the descendant will be unchanged at the time of this event firing. If the descendant is also a direct child of the parent, this event will fire before
Instance.ChildRemoved.If a descendant has children, this event fires with the descendant first, followed by its descendants.
Warning
This event fires with the descendant object that is being removed. Attempting to set the
Parentof the descendant to something else will fail. Below is an example that demonstrates this:local Workspace = game:GetService("Workspace") Workspace.DescendantRemoving:Connect(function(descendant) -- Do not manipulate the parent of the descendant in this function! -- This event fires BECAUSE the parent was manipulated, and the change hasn't happened yet -- Therefore, it is problematic to change the parent like this: descendant.Parent = game end) local part = Instance.new("Part") part.Parent = Workspace part.Parent = nilSee also
DescendantAdded.Destroying
Instance.Destroying:Connect(function())Fires immediately before (or is deferred until after) the instance is destroyed viaInstance.Destroy.The
Instancewill never be deleted from memory while a connected function is still using it. However, if the function yields at any point, theInstanceand its descendants will be parented tonil.If the
Workspace.SignalBehaviorproperty is set toSignalBehavior.Immediate, this event fires immediately before theInstanceor one of its ancestors is destroyed withInstance.Destroy.If the
Workspace.SignalBehaviorproperty is set toSignalBehavior.Deferred, this event fires at the next resumption point, which will be after theInstanceor one of its ancestors is destroyed withInstance.Destroy.With
Deferredbehavior, connecting a script to its ownInstance.Destroyingevent is problematic, as the script will be destroyed before the callback can be called (meaning it will not execute).When deleting an
Instancein Studio, such as manually deleting through the Explorer or through a plugin, theInstanceisn't destroyed. Instead, the parent is set tonilwhich you can track withInstance.AncestryChanged.StyledPropertiesChanged
Instance.StyledPropertiesChanged:Connect(function())Fires whenever any style property is changed on the instance, including when a property is set tonil.This event fires whenever any style property is changed on the instance, including when a property is set to
nil.
Reference text from the Roblox Creator Documentation, licensed CC BY 4.0, reorganized by rbxtoolshub.com · Studio 0.743.0.7431133.