Questions about CollectionService

Hello! I have a few questions about CollectionService.

  1. Can you run a function whenever any tag is added to any part?
  2. Is it possible to get a table of all the tagged parts in the game?

Thanks for taking the time to read this

1 Like

As much as I know, you have to define the actual tag that you want, there doesn’t appear to be any universal functions or events that fire for all tagged objects.

However, it isn’t hard to make a module or framework store all the tags you’ll be using and then create methods in that module that handle your specific goals.

e.g:

local tagHandler = {}

local tags = {"Tag1", "Tag2", "Tag3"}
local event_listeners = {}

local CollectionService = game:GetService("CollectionService")

function tagHandler:Init_Tag_Events()
--//Create events that fire when ever any specified tag is added to an object
for _, tag in pairs(tags) do
local listener;
listener = CollectionService:GetInstanceAddedSignal(tag):Connect(function(instance)
print(instance.Name.." was tagged with "..tag)
end)
end
end

function tagHandler:Get_All_Tagged_Parts() --//Returns an entire table of all objects with any specified tag
local tagged_objects = {}

for _, tag in pairs(tags) do
for _, object in pairs(CollectionService:GetTagged(tag)) do
table.insert(tagged_objects, object)
end
end

return tagged_objects
end


return tagHandler

Hope this helps a bit. Forgive the indenting, Roblox makes it painfully hard to format code on here.

1 Like

Thank you for the reply! This helped a lot, I appreciate it.

1 Like