CollectionService

Show Deprecated
Not Creatable
Service

The CollectionService manages groups (collections) of instances with tags. Tags are sets of strings applied to objects that replicate from the server to the client and in Team Create. They are also serialized when places are saved. At the moment, tags are not visible within Roblox Studio except with the use of a tag-editing plugin.

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 objects, perhaps a script that uses CollectionService would be better. Here are a couple examples:

  • In an obstacle course with many bricks that kill players, don't paste the same script in all your kill bricks! Instead, tag them with "KillBrick". Then, have any brick tagged as such kill the player.
  • Players with a VIP game pass could have their Humanoid tagged "VIP", and be allowed through doors that only allow VIPs.
  • When creating a freeze-tag game, you could tag frozen players' Humanoid objects with a "Frozen" tag. Then, use a LocalScript to listen for the "Frozen" tag and create client-side visual effects to reduce the number of objects replicated from server to client.

When working with collections and tags, it's a good idea to use an object-oriented programming style. In almost all situations, tagged objects have their own identity, state and behavior. The pattern goes like this: when a tag is found (CollectionService:GetTagged() and CollectionService:GetInstanceAddedSignal()), create a Lua object with the Roblox instance. When it is removed (CollectionService:GetInstanceRemovedSignal()), call a cleanup/destroy method within the Lua object. See the code samples for a better idea of how this can be done.

Replication

When tags replicate, all tags on an object replicate at the same time. Therefore, if you set a tag on an object from the client then add/remove a different tag on the same object from the server, the client's local tags on the object 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.

Code Samples

CollectionService Door

1local CollectionService = game:GetService("CollectionService")
2
3local Door = {}
4Door.__index = Door
5Door.TAG_NAME = "Door"
6Door.OPEN_TIME = 2
7
8function Door.new(door)
9 -- Create a table which will act as our new door object.
10 local self = {}
11 -- Setting the metatable allows the table to access
12 -- the SetOpen, OnTouch and Cleanup methods even if we did not
13 -- add all of the functions ourself - this is because the
14 -- __index metamethod is set in the Door metatable.
15 setmetatable(self, Door)
16
17 -- Keep track of some door properties of our own
18 self.door = door
19 self.debounce = false
20
21 -- Initialize a Touched event to call a method of the door
22 self.touchConn = door.Touched:Connect(function(...)
23 self:OnTouch(...)
24 end)
25
26 -- Initialize the state of the door
27 self:SetOpen(false)
28
29 print("Initialized door: " .. door:GetFullName())
30
31 return self
32end
33
34function Door:SetOpen(isOpen)
35 if isOpen then
36 self.door.Transparency = 0.75
37 self.door.CanCollide = false
38 else
39 self.door.Transparency = 0
40 self.door.CanCollide = true
41 end
42end
43
44function Door:OnTouch(part)
45 if self.debounce then
46 return
47 end
48 local human = part.Parent:FindFirstChild("Humanoid")
49 if not human then
50 return
51 end
52 self.debounce = true
53 self:SetOpen(true)
54 task.wait(Door.OPEN_TIME)
55 self:SetOpen(false)
56 self.debounce = false
57end
58
59function Door:Cleanup()
60 self.touchConn:disconnect()
61 self.touchConn = nil
62end
63
64local doors = {}
65
66local doorAddedSignal = CollectionService:GetInstanceAddedSignal(Door.TAG_NAME)
67local doorRemovedSignal = CollectionService:GetInstanceRemovedSignal(Door.TAG_NAME)
68
69local function onDoorAdded(door)
70 if door:IsA("BasePart") then
71 -- Create a new Door object and save it
72 -- The door class will take over from here!
73 doors[door] = Door.new(door)
74 end
75end
76
77local function onDoorRemoved(door)
78 if doors[door] then
79 doors[door]:Cleanup()
80 doors[door] = nil
81 end
82end
83
84-- Listen for existing tags, tag additions and tag removals for the door tag
85for _, inst in pairs(CollectionService:GetTagged(Door.TAG_NAME)) do
86 onDoorAdded(inst)
87end
88doorAddedSignal:Connect(onDoorAdded)
89doorRemovedSignal:Connect(onDoorRemoved)

Summary

Properties

Events

Methods

AddTag(instance: Instance, tag: string): nil  

Applies a tag to an Instance.


Returns a signal that fires when a given tag is added to an object.


Returns a signal that fires when a given tag is removed from an instance.


Returns an array of objects in the game with a given tag.

GetTags(instance: Instance): Array  

Gets an array of all tags applied to a given object.

HasTag(instance: Instance, tag: string): boolean  

Check whether an object has a given tag.

RemoveTag(instance: Instance, tag: string): nil  

Removes a tag from an instance.

Properties

Events

TagAdded

Parameters

tag: string

TagRemoved

Parameters

tag: string

Methods

AddTag

AddTag will apply a tag to an Instance, doing nothing if the tag is already applied to the instance. Successfully adding a tag will fire a signal created by CollectionService:GetInstanceAddedSignal() with the given tag.

Warning: When tagging an instance, it is common that some resources are used to give the tag its functionality, e.g. event connections or tables. To prevent memory leaks, it is a good idea to clean these up (disconnect, set to nil, etc) when no longer needed for a tag. Do this when calling CollectionService:RemoveTag(), calling Instance:Destroy() or in a function connected to a signal returned by CollectionService:GetInstanceRemovedSignal().

Parameters

instance: Instance
tag: string

Returns

GetAllTags

Returns

GetInstanceAddedSignal

GetInstanceAdded is given a tag (a string) and 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 CollectionService:GetTagged() to get a list of objects that already have a tag (and thus won't fire the event if they already are in the DataModel).

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

Parameters

tag: string

The tag to watch for.


Returns

An event that fires when you add the tag to an instance.

Code Samples

Deadly Bricks using CollectionService

1local CollectionService = game:GetService("CollectionService")
2
3local tag = "Deadly"
4
5local function onDeadlyPartTouched(otherPart)
6 if not otherPart.Parent then
7 return
8 end
9 local human = otherPart.Parent:FindFirstChildOfClass("Humanoid")
10 if human then
11 human.Health = 0
12 end
13end
14
15-- Save the connections so they can be disconnected when the tag is removed
16-- This table maps BaseParts with the tag to their Touched connections
17local connections = {}
18
19local function onInstanceAdded(object)
20 -- Remember that any tag can be applied to any object, so there's no
21 -- guarantee that the object with this tag is a BasePart.
22 if object:IsA("BasePart") then
23 connections[object] = object.Touched:Connect(onDeadlyPartTouched)
24 end
25end
26
27local function onInstanceRemoved(object)
28 -- If we made a connection on this object, disconnect it (prevent memory leaks)
29 if connections[object] then
30 connections[object]:Disconnect()
31 connections[object] = nil
32 end
33end
34
35-- Listen for this tag being applied to objects
36CollectionService:GetInstanceAddedSignal(tag):Connect(onInstanceAdded)
37CollectionService:GetInstanceRemovedSignal(tag):Connect(onInstanceRemoved)
38
39-- Also detect any objects that already have the tag
40for _, object in pairs(CollectionService:GetTagged(tag)) do
41 onInstanceAdded(object)
42end

GetInstanceRemovedSignal

GetInstanceRemoved is given a tag (a string) and 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 objects that once had tags, such as disconnecting connections.

See also CollectionService:GetInstanceAddedSignal(), which returns an event that fires under similar conditions.

Parameters

tag: string

The tag to watch for.


Returns

An event that fires when you remove the tag from an instance.

Code Samples

Deadly Bricks using CollectionService

1local CollectionService = game:GetService("CollectionService")
2
3local tag = "Deadly"
4
5local function onDeadlyPartTouched(otherPart)
6 if not otherPart.Parent then
7 return
8 end
9 local human = otherPart.Parent:FindFirstChildOfClass("Humanoid")
10 if human then
11 human.Health = 0
12 end
13end
14
15-- Save the connections so they can be disconnected when the tag is removed
16-- This table maps BaseParts with the tag to their Touched connections
17local connections = {}
18
19local function onInstanceAdded(object)
20 -- Remember that any tag can be applied to any object, so there's no
21 -- guarantee that the object with this tag is a BasePart.
22 if object:IsA("BasePart") then
23 connections[object] = object.Touched:Connect(onDeadlyPartTouched)
24 end
25end
26
27local function onInstanceRemoved(object)
28 -- If we made a connection on this object, disconnect it (prevent memory leaks)
29 if connections[object] then
30 connections[object]:Disconnect()
31 connections[object] = nil
32 end
33end
34
35-- Listen for this tag being applied to objects
36CollectionService:GetInstanceAddedSignal(tag):Connect(onInstanceAdded)
37CollectionService:GetInstanceRemovedSignal(tag):Connect(onInstanceRemoved)
38
39-- Also detect any objects that already have the tag
40for _, object in pairs(CollectionService:GetTagged(tag)) do
41 onInstanceAdded(object)
42end

GetTagged

GetTagged returns an array of objects with a given tag which are descendants of the DataModel (game). Such tags have been added using CollectionService:AddTag(), and removing a tag using CollectionService:RemoveTag() will ensure this method does not return them. Although the name of this method is past-tense, this method only returns objects presently tagged with the given tag. It will not return objects that once had a tag but no longer have it.

If you want to detect all objects with a tag, both present and future, use this method to iterate over objects while also making a connection to a signal returned by CollectionService.GetinstanceAddedSignal.

This method does not guarantee any ordering of the returned objects. Additionally, it is possible that objects can have the given tag assigned to them, but not be a descendant of the DataModel, i.e. its parent is nil. This method will not return such objects.

Parameters

tag: string

The tag to search for.


Returns

An array of all instances with the tag.

Code Samples

Deadly Bricks using CollectionService

1local CollectionService = game:GetService("CollectionService")
2
3local tag = "Deadly"
4
5local function onDeadlyPartTouched(otherPart)
6 if not otherPart.Parent then
7 return
8 end
9 local human = otherPart.Parent:FindFirstChildOfClass("Humanoid")
10 if human then
11 human.Health = 0
12 end
13end
14
15-- Save the connections so they can be disconnected when the tag is removed
16-- This table maps BaseParts with the tag to their Touched connections
17local connections = {}
18
19local function onInstanceAdded(object)
20 -- Remember that any tag can be applied to any object, so there's no
21 -- guarantee that the object with this tag is a BasePart.
22 if object:IsA("BasePart") then
23 connections[object] = object.Touched:Connect(onDeadlyPartTouched)
24 end
25end
26
27local function onInstanceRemoved(object)
28 -- If we made a connection on this object, disconnect it (prevent memory leaks)
29 if connections[object] then
30 connections[object]:Disconnect()
31 connections[object] = nil
32 end
33end
34
35-- Listen for this tag being applied to objects
36CollectionService:GetInstanceAddedSignal(tag):Connect(onInstanceAdded)
37CollectionService:GetInstanceRemovedSignal(tag):Connect(onInstanceRemoved)
38
39-- Also detect any objects that already have the tag
40for _, object in pairs(CollectionService:GetTagged(tag)) do
41 onInstanceAdded(object)
42end

GetTags

GetTags is given an instance and returns an array of strings, which are the tags applied to the given object.


1local CollectionService = game:GetService("CollectionService")
2local object = workspace.Model
3local tags = CollectionService:GetTags(object)
4print("The object " .. object:GetFullName() .. " has tags: " .. table.concat(tags, ", "))
5

This method is useful when you want to do something with multiple tags at once on an object. However, it would be inefficient to use this method to check for the existence of a single tag. For this, use CollectionService:HasTag() to check for a single tag.

Parameters

instance: Instance

The object whose tags should be returned.


Returns

An array of strings which are the tags applied to the given object.

Code Samples

Using Tags and CollectionService

1local CollectionService = game:GetService("CollectionService")
2local object = workspace.Part
3
4-- Add a tag
5CollectionService:AddTag(object, "Deadly")
6
7-- Query for a tag
8if CollectionService:HasTag(object, "Deadly") then
9 print(object:GetFullName() .. " is deadly")
10end
11
12-- List tags on an object
13local tags = CollectionService:GetTags(object)
14print("The object " .. object:GetFullName() .. " has tags: " .. table.concat(tags, ", "))
15
16-- Remove a tag
17CollectionService:RemoveTag(object, "Deadly")

HasTag

HasTag returns whether a given object has a tag.

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

Parameters

instance: Instance

The instance to check for the presence of a tag.

tag: string

The tag to check for.


Returns

Whether the instance has the tag.

Code Samples

Using Tags and CollectionService

1local CollectionService = game:GetService("CollectionService")
2local object = workspace.Part
3
4-- Add a tag
5CollectionService:AddTag(object, "Deadly")
6
7-- Query for a tag
8if CollectionService:HasTag(object, "Deadly") then
9 print(object:GetFullName() .. " is deadly")
10end
11
12-- List tags on an object
13local tags = CollectionService:GetTags(object)
14print("The object " .. object:GetFullName() .. " has tags: " .. table.concat(tags, ", "))
15
16-- Remove a tag
17CollectionService:RemoveTag(object, "Deadly")

RemoveTag

RemoveTag will remove a tag from an instance. This method will not throw an error if the object did not have the tag in the first place. Successfully removing a tag will fire a signal created by CollectionService:GetInstanceRemovedSignal() with the given tag.

When removing a tag, it is common that some resources are used to give the tag its functionality, e.g. event connections or tables. To prevent memory leaks, it is a good idea to clean these up (disconnect, set to nil, etc) when no longer needed for a tag.

Parameters

instance: Instance

The instance to remove the tag from.

tag: string

The tag to remove from the instance.


Returns

Code Samples

Using Tags and CollectionService

1local CollectionService = game:GetService("CollectionService")
2local object = workspace.Part
3
4-- Add a tag
5CollectionService:AddTag(object, "Deadly")
6
7-- Query for a tag
8if CollectionService:HasTag(object, "Deadly") then
9 print(object:GetFullName() .. " is deadly")
10end
11
12-- List tags on an object
13local tags = CollectionService:GetTags(object)
14print("The object " .. object:GetFullName() .. " has tags: " .. table.concat(tags, ", "))
15
16-- Remove a tag
17CollectionService:RemoveTag(object, "Deadly")