Service · inherits Instance
CollectionService
A service which manages instance collections using assigned tags.
About CollectionService
CollectionService manages groups (collections) of instances with tags.
Tags are sets of strings applied to instances that replicate from the server
to the client. They are also serialized when places are saved.
The primary use of CollectionService is to register instances with specific
tags that you can use to extend their behavior. If you find yourself adding
the same script to many different instances, a script that uses
CollectionService may be better.
Tags can be added or removed through this class' methods such as
AddTag() or
RemoveTag(). They can also be managed
directly in Studio through the
Tags section of an instance's
properties.
Replication
When tags replicate, all tags on an instance replicate at the same time.
Therefore, if you set a tag on an instance from the client then add/remove a
different tag on the same instance from the server, the client's local
tags on the instance are overwritten. In
StreamingEnabled places, instances can be
unloaded as they leave the client's streamed area. If such an instance
re-enters the streamed area, properties and tags will be re-synchronized from
the server. This can cause changes made by LocalScripts to
be overwritten/removed.
Methods 9
AddTag
(instance: Instance, tag: string) → ()Applies a tag to anInstance.This method applies a tag to an
Instance, doing nothing if the tag is already applied to that instance. Successfully adding a tag will fire a signal created byGetInstanceAddedSignal()with 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 callingRemoveTag(), callingInstance.Destroyor in a function connected to a signal returned byGetInstanceRemovedSignal().
CreateCollection
(query: string, root: Instance = nil) → CollectionCreates aCollectionthat tracks every instance matching a query.This method creates a
Collection, a live, query-based group of instances. Unlike tag-based methods such asGetTagged()which return a fixed array at the moment they are called, aCollectioncontinuously tracks which instances matchqueryand notifies you as instances enter and leave the result set.The
querystring is a CSS-inspired selector that follows the same selector conventions used byQueryDescendants()and theStyleRulestyling selectors. Filters stack conjunctively, combinators express hierarchy, and comma-separated selectors form a union:ClassName— Instances of that class (usesIsA()), for examplePartorModel.#Name— Instances with a matchingName..Tag— Instances carrying aCollectionServicetag.[Property = value]— Instances whose property equals a value.[$Attribute]or[$Attribute = value]— Instances that have an attribute, optionally matching a value.A > B(direct child) andA >> B(any descendant) combinators.:has(...)and:not(...)pseudoclasses.
The rightmost selector in a chain identifies the matched instance, so
Folder > Parttracks the parts, not the folders.local CollectionService = game:GetService("CollectionService") -- Track every Part tagged "KillBrick" anywhere under Workspace local killBricks: Collection = CollectionService:CreateCollection("Part.KillBrick") -- When a part joins the collection, make it glow red -- OnAdded fires once for each part already matching, then again for each new match function killBricks.OnAdded(brick: Part) brick.Material = Enum.Material.Neon brick.Color = Color3.new(1, 0, 0) end -- Kill any humanoid that touches a matched part function killBricks.OnTouched(brick: Part, otherPart: BasePart) local character: Instance? = otherPart.Parent local humanoid = character and character:FindFirstChildOfClass("Humanoid") if humanoid then humanoid.Health = 0 end end -- Fires when a part stops matching (tag removed, reparented out, or destroyed) function killBricks.OnRemoved(brick: Part) print("Deactivating", brick:GetFullName()) endNotes
- The collection remains active until you call
Destroy()or itsrootis destroyed. - Lifecycle callbacks are queued rather than invoked synchronously, so a
newly assigned
OnAddedmay fire on a later resumption point rather than during the assignment itself.
GetAllTags
() → ArrayReturns an array of all tags in the experience.Returns an array of all tags that currently have at least one tagged instance inside the
DataModel. The returned array does not guarantee any particular ordering.A tag appears in the result as soon as any instance bearing it enters the
DataModel(for example by being parented toWorkspace), and it is removed from the result once the last instance with that tag leaves theDataModelor has the tag removed. This means callingGetAllTags()immediately after removing the last instance with a given tag will no longer include that tag.GetInstanceAddedSignal
(tag: string) → RBXScriptSignalReturns a signal that fires when a given tag is added to an instance.Given a tag (string), this method returns a signal which fires under two conditions:
The tag is assigned to an instance within the
DataModelusingCollectionService.AddTagorInstance.AddTag.An instance with the given tag is added as a descendant of the
DataModel, for example by settingInstance.Parentor similar.
Subsequent calls to this method with the same tag return the same signal object. Consider also calling
GetTagged()to get a list of instances that already have a tag (and thus won't fire the event if they already are in theDataModel).See also
GetInstanceRemovedSignal()which returns an event that fires under similar conditions.GetInstanceRemovedSignal
(tag: string) → RBXScriptSignalReturns a signal that fires when a given tag is removed from an instance.Given a tag (string), this method returns a signal which fires under two conditions:
The tag is removed from an instance within the
DataModelusingCollectionService.RemoveTagorInstance.RemoveTag.An instance with the given tag is removed as a descendant of the
DataModel, for example by un‑settingInstance.Parentor similar.
Subsequent calls to this method with the same tag return the same signal object. The signal is useful for cleaning up resources used by instances that once had tags, such as disconnecting connections.
See also
GetInstanceAddedSignal()which returns an event that fires under similar conditions.GetTagged
(tag: string) → InstancesReturns an array of instances in the game with a given tag.This method returns an array of instances with a given tag which are descendants of the
DataModel. Removing a tag usingCollectionService.RemoveTagorInstance.RemoveTagensures this method does not return them.If you want to detect all instances with a tag, both present and future, use this method to iterate over instances while also making a connection to a signal returned by
GetInstanceAddedSignal().This method does not guarantee any ordering of the returned instances. Additionally, it's possible that instances can have the given tag assigned to them but not be a descendant of the
DataModel, for example its parent isnil; this method will not return such instances.GetTags
(instance: Instance) → ArrayGets an array of all tags applied to a given instance.Given an
Instance, this method returns an array of strings which are the tags applied to the instance.This method is useful when you want to do something with multiple instance tags at once, but it's inefficient to check for the existence of a single tag. For this, use
HasTag()to check for a single tag.RemoveTag
(instance: Instance, tag: string) → ()Removes a tag from an instance.This method removes a tag from an instance. Successfully removing a tag will fire a signal created by
GetInstanceRemovedSignal()with the given tag.When removing a tag, 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.
Events 2
TagAdded
CollectionService.TagAdded:Connect(function(tag))Fires when a tag is added to an instance and the added tag is the only occurrence of that tag in the place.This event fires when a tag transitions from being unused to being in use — specifically, when a tag is applied to an instance inside the
DataModeland no other instance in theDataModelpreviously had that tag. The event passes the tag name as its parameter.TagAddedfires once per tag lifetime, not once per instance. To detect every individual instance that receives a particular tag, useGetInstanceAddedSignal()instead.The event fires asynchronously (deferred to the next resumption point), not synchronously inside the
AddTag()call that triggered it.TagRemoved
CollectionService.TagRemoved:Connect(function(tag))Fires when a tag is removed from an instance and the removed tag is no longer used anywhere in the place.This event fires when the last instance bearing a given tag leaves the
DataModelor has the tag removed, meaning no instance in theDataModelstill carries that tag. The event passes the tag name as its parameter.TagRemovedfires once per tag lifetime, not once per instance. To detect every individual instance that loses a particular tag, useGetInstanceRemovedSignal()instead.The event fires asynchronously (deferred to the next resumption point), not synchronously inside the removal operation that triggered it.
CollectionService also has every member of Instance. Deprecated and Roblox-only members are hidden.
Reference text from the Roblox Creator Documentation, licensed CC BY 4.0, reorganized by rbxtoolshub.com · Studio 0.743.0.7431133.