Using .Touched with :GetTagged()

Hey!
I’m quite new to using the collection service so i’ve been experimenting a bunch with it recently and: i came to question whether or not it’d be possible to detect whenever a tagged part gets touched.

I’ve tried a couple methods but to no avail. If anyone could help that’d be great! And if you have any questions, i’d be glad to answer.

local function onTaggedPartTouched(part: BasePart, tag: string, callback: (otherPart: BasePart) -> ()): RBXScriptConnection
    return part.Touched:Connect(function(otherPart: BasePart)
        if otherPart:HasTag(tag) then
            callback(otherPart)
        end
    end)
end
local function onTouched(otherPart: BasePart)
    print(`A part with the "Test" tag touched!`)
end


onTaggedPartTouched(workspace.Part, "Test", onTouched)
1 Like

Hello, beware that touched event only works with parts that are both anchored set to false and have the CanCollide property to true, so don’t make the same mistake I made. Use GetPartBoundsInBox if you want any one of those properties a different value.

This is not entirely correct. As per the documentation:

“This event only fires as a result of physical movement, so it will not fire if the CFrame property was changed such that the part overlaps another part. This also means that at least one of the parts involved must not be Anchored at the time of the collision.”

CanCollide does not affect the event either

You could just loop through all of the tagged parts, like this:

local parts = CollectionService:GetTagged("SomeTag")

for _, part in parts do
    part.Touched:Connect(function()
        print("Tagged part touched!")
    end)
end
2 Likes

Ah, lol, I misread OP. This is even more trivial. I’m even more curious as to what went wrong

No you didn’t, that’s what i was looking for pretty much, i’ll be testing and modifying what you’ve sent to my liking. Thank you! (Also thanks to Alexander)

1 Like

HA. Well that worked out then. Let me know if you have any issues; likewise, if the solution works for you, don’t forget to mark it so!