Reference API Roblox

Engine API

Website

Related

Reference API Roblox

CollectionService

A service which manages instance collections using assigned tags.

This class is not creatable. Instances of this class cannot be created with Instance.new.
This class is a service. It is a singleton that may be acquired with GetService.
Tags: [NotCreatable, Service]

Member index 16

HistoryMember
637AddTag(instance: Instance, tag: string): null
734CreateCollection(query: string, root: Instance = Instance): CollectionHandle
525GetAllTags(): Array
731GetCollection(class: string): Instances
462GetInstanceAddedSignal(tag: string): RBXScriptSignal
462GetInstanceRemovedSignal(tag: string): RBXScriptSignal
732GetTagAddedSignal(instance: Instance): RBXScriptSignal
732GetTagRemovedSignal(instance: Instance): RBXScriptSignal
648GetTagged(tag: string): Instances
637GetTags(instance: Instance): Array
637HasTag(instance: Instance, tag: string): bool
637RemoveTag(instance: Instance, tag: string): null
731ItemAdded(instance: Instance)
731ItemRemoved(instance: Instance)
525TagAdded(tag: string)
525TagRemoved(tag: string)
inherited from Instance
731Archivable: bool
731Capabilities: SecurityCapabilities
731IsInSandbox: bool
731Name: string
731Parent: Instance
731PredictionMode: PredictionMode
731Sandboxed: bool
731UniqueId: UniqueId
576AddTag(tag: string): null
573ClearAllChildren(): null
462Clone(): Instance
573Destroy(): null
486FindFirstAncestor(name: string): Instance
486FindFirstAncestorOfClass(className: string): Instance
486FindFirstAncestorWhichIsA(className: string): Instance
486FindFirstChild(name: string, recursive: bool = false): Instance
486FindFirstChildOfClass(className: string): Instance
486FindFirstChildWhichIsA(className: string, recursive: bool = false): Instance
486FindFirstDescendant(name: string): Instance
563GetActor(): Actor
486GetAttribute(attribute: string): Variant
462GetAttributeChangedSignal(attribute: string): RBXScriptSignal
631GetAttributes(): Dictionary
648GetChildren(): Instances
462GetDebugId(scopeLength: int = 4): string
707GetDescendants(): Instances
486GetFullName(): string
706GetStyled(name: string, selector: string?): Variant
657GetStyledPropertyChangedSignal(property: string): RBXScriptSignal
576GetTags(): Array
576HasTag(tag: string): bool
486IsAncestorOf(descendant: Instance): bool
486IsDescendantOf(ancestor: Instance): bool
664IsPropertyModified(property: string): bool
698QueryDescendants(selector: string): Instances
573Remove(): null
576RemoveTag(tag: string): null
664ResetPropertyToDefault(property: string): null
573SetAttribute(attribute: string, value: Variant): null
462WaitForChild(childName: string, timeOut: double): Instance
731children(): Instances
731clone(): Instance
731destroy(): null
731findFirstChild(name: string, recursive: bool = false): Instance
731getChildren(): Instances
731isDescendantOf(ancestor: Instance): bool
731remove(): null
462AncestryChanged(child: Instance, parent: Instance)
462AttributeChanged(attribute: string)
462ChildAdded(child: Instance)
462ChildRemoved(child: Instance)
462DescendantAdded(descendant: Instance)
462DescendantRemoving(descendant: Instance)
500Destroying()
657StyledPropertiesChanged()
731childAdded(child: Instance)
inherited from Object
731ClassName: string
731className: string
647GetPropertyChangedSignal(property: string): RBXScriptSignal
647IsA(className: string): bool
731isA(className: string): bool
647Changed(property: string)

Description

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.

History 52

Members 16

AddTag

Parameters (2)
instanceInstance
tagstring
Returns (1)
null

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 by GetInstanceAddedSignal() 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 calling RemoveTag(), calling Instance:Destroy() or in a function connected to a signal returned by GetInstanceRemovedSignal().

This function has a custom internal state. It may behave in a non-standard way.

History 4

Tags: [CustomLuaState]

CreateCollection

Parameters (2)Default
querystring
rootInstanceInstance
Returns (1)
CollectionHandle

This method creates a Collection, a live, query-based group of instances. Unlike tag-based methods such as GetTagged() which return a fixed array at the moment they are called, a Collection continuously tracks which instances match query and notifies you as instances enter and leave the result set.

The query string is a CSS-inspired selector that follows the same selector conventions used by QueryDescendants() and the StyleRule styling selectors. Filters stack conjunctively, combinators express hierarchy, and comma-separated selectors form a union:

  • ClassName — Instances of that class (uses IsA()), for example Part or Model.
  • #Name — Instances with a matching Name.
  • .Tag — Instances carrying a CollectionService tag.
  • [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) and A >> B (any descendant) combinators.
  • :has(...) and :not(...) pseudoclasses.

The rightmost selector in a chain identifies the matched instance, so Folder > Part tracks the parts, not the folders.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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())
end

Notes

  • The collection remains active until you call Destroy() or its root is destroyed.
  • Lifecycle callbacks are queued rather than invoked synchronously, so a newly assigned OnAdded may fire on a later resumption point rather than during the assignment itself.

History 1

GetAllTags

Parameters (0)
No parameters.
Returns (1)
Array

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 to Workspace), and it is removed from the result once the last instance with that tag leaves the DataModel or has the tag removed. This means calling GetAllTags() immediately after removing the last instance with a given tag will no longer include that tag.

History 1

GetCollection

Parameters (1)
classstring
Returns (1)
Instances

This function returns all instances of a given class which are in the DataModel. Only works for Configuration, CustomEvent, CustomEventReceiver, Dialog, and VehicleSeat.

This function is deprecated. It exists only for backward compatibility, and should not be used for new work. GetTagged should be used instead.

History 9

Tags: [Deprecated]

GetInstanceAddedSignal

Parameters (1)
tagstring
Returns (1)
RBXScriptSignal

Given a tag (string), this method returns a signal which fires under two conditions:

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 the DataModel).

See also GetInstanceRemovedSignal() which returns an event that fires under similar conditions.

History 2

GetInstanceRemovedSignal

Parameters (1)
tagstring
Returns (1)
RBXScriptSignal

Given a tag (string), this method returns a signal which fires under two conditions:

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.

History 2

GetTagAddedSignal

Parameters (1)
instanceInstance
Returns (1)
RBXScriptSignal

History 1

GetTagRemovedSignal

Parameters (1)
instanceInstance
Returns (1)
RBXScriptSignal

History 1

GetTagged

Parameters (1)
tagstring
Returns (1)
Instances

This method returns an array of instances with a given tag which are descendants of the DataModel. Removing a tag using CollectionService:RemoveTag() or Instance:RemoveTag() ensures 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 is nil; this method will not return such instances.

History 4

GetTags

Parameters (1)
instanceInstance
Returns (1)
Array

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.

This function has a custom internal state. It may behave in a non-standard way.

History 4

Tags: [CustomLuaState]

HasTag

Parameters (2)
instanceInstance
tagstring
Returns (1)
bool

This method returns whether a given Instance has a tag.

By extension, any tags returned by a call to GetTags() on an instance will return true when used with this method.

This function has a custom internal state. It may behave in a non-standard way.

History 4

Tags: [CustomLuaState]

ItemAdded

Parameters (1)
instanceInstance

This function fires when a Configuration, CustomEvent, CustomEventReceiver, Dialog, or VehicleSeat is added to the DataModel.

This event is deprecated. It exists only for backward compatibility, and should not be used for new work. GetInstanceAddedSignal should be used instead.

History 6

Tags: [Deprecated]

ItemRemoved

Parameters (1)
instanceInstance

This function fires when a Configuration, CustomEvent, CustomEventReceiver, Dialog, or VehicleSeat is removed from the DataModel.

This event is deprecated. It exists only for backward compatibility, and should not be used for new work. GetInstanceRemovedSignal should be used instead.

History 6

Tags: [Deprecated]

RemoveTag

Parameters (2)
instanceInstance
tagstring
Returns (1)
null

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.

This function has a custom internal state. It may behave in a non-standard way.

History 4

Tags: [CustomLuaState]

TagAdded

Parameters (1)
tagstring

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 DataModel and no other instance in the DataModel previously had that tag. The event passes the tag name as its parameter.

TagAdded fires once per tag lifetime, not once per instance. To detect every individual instance that receives a particular tag, use GetInstanceAddedSignal() instead.

The event fires asynchronously (deferred to the next resumption point), not synchronously inside the AddTag() call that triggered it.

History 1

TagRemoved

Parameters (1)
tagstring

This event fires when the last instance bearing a given tag leaves the DataModel or has the tag removed, meaning no instance in the DataModel still carries that tag. The event passes the tag name as its parameter.

TagRemoved fires once per tag lifetime, not once per instance. To detect every individual instance that loses a particular tag, use GetInstanceRemovedSignal() instead.

The event fires asynchronously (deferred to the next resumption point), not synchronously inside the removal operation that triggered it.

History 1

Settings