Using CollectionService on instances that are cloned

I have tagged parts in my game, and they all work just fine with CollectionService when the parts are placed in during testing. However, when I try and clone those instances, the collection service code doesn’t seem to work anymore. Does the CollectionService not detect/add objects to the pile that have been cloned? If not, what would be a work-around for this?

1 Like

If the part’s aren’t keeping the tag, then just add the tag after you clone it.

local basePart = -- your part here
local clonedPart = basePart:CLone()
-- change params here
clonedPart:AddTag(-- your tag)
1 Like

I’m assuming you’re using CollectionService:GetTagged(), a function that returns a table of all instances in the game that has a given tag.

You can think of this like a for loop going through a folder’s children. If you add functionality to each object in the loop, and then add another part to the folder, the part obviously won’t receive functionality as it wasn’t a child of the folder at the time of the loop. Instead, you’d have to use ChildAdded to add the same functionality to the new part.

The same is true with CollectionService. If a new tagged part is added, it won’t update instantly. There are a couple different workarounds for this, but the most performant would probably be this:

local function AddPartFunctionality(part)
	-- do stuff to part
end

for i,v in pairs(CollectionService:GetTagged("Tag name")) do
	AddPartFunctionality(v)
end

CollectionService:GetInstanceAddedSignal("Tag name"):Connect(function(object)
	AddPartFunctionality(object)
end)

GetInstanceAddedSignal returns an object that a given tag was added to. So whenever you clone a part, make sure it doesn’t have any tags, then tag it after it’s been cloned.

1 Like

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