PcoWSkbVqDnWTu_dm2ix
Collapse Sidebar

GetTagged

GetTagged returns a table 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

Name Type Default Description

tag

Returns

Return Type Summary

Code Samples


Deadly Bricks using CollectionService

This code sample causes any BasePart with the tag “Deadly” to kill any Humanoid that touches it. It does this using a common pattern with CollectionService: listen for all parts with the tag, and make a connection. When the tag is removed, disconnect. Instead of copying the same kill script into many bricks, use this pattern instead!

local CollectionService = game:GetService("CollectionService")
local tag = "Deadly"

local function onDeadlyPartTouched(otherPart)
	if not otherPart.Parent then return end
	local human = otherPart.Parent:FindFirstChildOfClass("Humanoid")
	if human then
		human.Health = 0
	end
end

-- Save the connections so they can be disconnected when the tag is removed
-- This table maps BaseParts with the tag to their Touched connections
local connections = {}

local function onInstanceAdded(object)
	-- Remember that any tag can be applied to any object, so there's no
	-- guarantee that the object with this tag is a BasePart.
	if object:IsA("BasePart") then
		connections[object] = object.Touched:Connect(onDeadlyPartTouched)
	end
end

local function onInstanceRemoved(object)
	-- If we made a connection on this object, disconnect it (prevent memory leaks)
	if connections[object] then
		connections[object]:disconnect()
		connections[object] = nil
	end
end

-- Listen for this tag being applied to objects
CollectionService:GetInstanceAddedSignal(tag):Connect(onInstanceAdded)

-- Also detect any objects that already have the tag
for _, object in pairs(CollectionService:GetTagged(tag)) do
	onInstanceAdded(object)
end