How can I update Collected Tag from collection service

If a new part is added after the game start it won’t be collected in tag.

	local parts = collectionService:GetTagged("killBrick")
	for _,part in  ipairs(parts) do
		part.Touched:Connect(function(otherPart)
			if otherPart.Parent:FindFirstChild("Humanoid") then
				otherPart.Parent.Humanoid.Health = 0
			end
		end)
	end

So I made a temporary fix to it by just updating it every few second.

while true do
	task.wait(5)
	local parts = collectionService:GetTagged("killBrick")
	for _,part in  ipairs(parts) do
		part.Touched:Connect(function(otherPart)
			if otherPart.Parent:FindFirstChild("Humanoid") then
				otherPart.Parent.Humanoid.Health = 0
			end
		end)
	end
end

But it started to lag after a while. It would run Touched on the same part multiple time.

image

How can I make it so that it check tag on new part that is added later but not on the same part multiple time?

2 Likes

This method is really inefficient. It would be better to add a script to a brick that you put in serverstorage that has:

script.Parent.Touched:Connect(function(otherpart)
if otherpart.Parent:FindFirstChild(“Humanoid”) then
otherpart.Parent:FindFirstChild(“Humanoid”).Health = 0
end)

1 Like

Also, if you still wanted to go with your approach, you wouldn’t be able to use an event like tagadded because the tag name has to be the only one with that name(unique), so if there were a million “killbrick” tags it wouldn’t be able to detect that. You could get around that by making every name unique with different characters but that’s overkill. I also didn’t completely understand what you were trying to say at the bottom of your post. If you want to add a stringvalue to each part that is a kill brick saying “killbrick” that would also work. Just letting you know you have options here.

1 Like

Hey @pyojun123 ! There is a way to detect when the part is added to the collection. So your code may look like this:

local CollectionService = game:GetService("CollectionService")

-- Add a function to not replicate the code multiple times
local function AddKillingConnection(Part)
    Part.Touched:Connect(function(OtherPart)
		if OtherPart.Parent:FindFirstChild("Humanoid") then
			OtherPart.Parent.Humanoid.Health = 0
		end
	end)
end

-- For all existing parts with tag "killBrick" add the killing connection
for _, Part in CollectionService:GetTagged("killBrick") do
     AddKillingConnection(Part)
end

-- For any new parts with the tag "killBrick" add the killing connection
CollectionService:GetInstanceAddedSignal("killBrick"):Connect(function(Part)
	AddKillingConnection(Part)
end)

Hope that helps!

4 Likes

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