Using Tags/CollectionService

So I have 3 CollectionService tags, CrateOfApples, CrateOfBananas, and CrateOfOranges. My issue is how would I :GetTagged() of multiple tags in one line of code, without copy and pasting the working code and just replacing it for each of the tags, if that makes sense.

I tried problem solving by using a table to see if that could work and it did not. Example:

local Tags = {
     "CrateOfApples",
     "CrateOfBananas",
     "CrateOfOranges"
}

for _, TaggedObject in pairs(CollectionService:GetTagged(Tags)) do
     --about 30 lines of code where cut out
end

Script that I’m using now: (I could just copy and paste this script two more times but I feel like theirs a better way of doing so.)

for _, TaggedObject in pairs(CollectionService:GetTagged("CrateOfApples")) do
     --about 30 lines of code where cut out
end
1 Like

There isn’t a function that can get all items based on a table of tags. The best you can do is make a function that does exactly that.

local function GetFromTags(Tags : {string}) : {Instance}
	local Items = {}
	
	for _, Tag in Tags do
		for _, Item in CollectionService:GetTagged(Tag) do
			if table.find(Items, Item) then
				continue -- Ignore to not add a duplicate.
			end
			
			table.insert(Items, Item)
		end
	end
	
	return Items
end

GetFromTags({"Your tags here."})

If you want the function to be usable in many scripts, use a ModuleScript and require() it in your Scripts.

2 Likes

Why not just loop through the tags

local Tags = {
     "CrateOfApples",
     "CrateOfBananas",
     "CrateOfOranges"
}

for _, Tag in pairs(Tags) do
    for _, TaggedObject in pairs(CollectionService:GetTagged(Tag)) do
         --about 30 lines of code where cut out
    end
end
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.