Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I correctly connect a script to Tagged Objects in CollectionService?

I was trying to test Tags and Collection Service. I have set-up the Tag using the Instance Tagging, and then added a block (say, Block1) to the tag.

On ServerScriptService, I have created a script with the following code:

local CollectionService = game:GetService("CollectionService")
local CollectionName = "PoppingBlocks" --The name of the Tag

local function onTouch()
     print("Touched object")
end

for _, object in pairs(CollectionService:GetTagged(CollectionName)) do	
	object.Touched:Connect(onTouch)
end

Expected: When I touch the object, console must print "Touched object"

Touching the object does not do anything. Furthermore, how do I pass more parameters on Touched event?

local CollectionService = game:GetService("CollectionService")
local CollectionName = "PoppingBlocks" --The name of the Tag

local function onTouch(object)
     print("Touched object " .. object.Name)
end

for _, object in pairs(CollectionService:GetTagged(CollectionName)) do
	
	object.Touched:Connect(onTouch(object)) --???
end

???: Doesn't the Touch event send 'hit' or 'otherpart' as a parameter? What would the 'object' parameter in the Connect() function be?

Also, how do I destroy the block? My original method was applying this script to the block manually, and then calling script.Parent

local this = script.Parent

local function onTouch()
     print("Touched object" .. this.Name .. ")
     this:Destroy()
end

this.Touched:Connect(onTouch)

This method simply worked. However, for obvious reasons, it was very tedious. I found myself editing one script, and copy-pasting it to every block I need.

1 answer

✓ Accepted answer

Im gonna try to answer this the best I can

(after the "Expected: When I touch the object, console must print "Touched object"" part) 1st question: object.Touched should work.

If you want to use premade parameters you could do something like this (this should also answer your second question in the comments):

-- code goes inside of the for loop

object.Touched:Connect(function(hit)
	-- you have access to both "hit" and "object" in here

	print(object:GetFullName() .." Touched ".. hit:GetFullName()) -- getfullname so you can get the path of the object
	object:Destroy() -- same thing as your request of this:Destroy()
end)

1 comment

0

Your assurance of "should worked" helped me a lot and forced me to try every other possible solution. I just had to call the loop again to update new objects in |CollectionService:GetTagged(CollectionName)|. Thank you!

This discussion is preserved as it was. New answers, comments, and votes are closed.