How to detect when multiple objects are touched?

How do I make it so that any part inside a folder does the exact same thing when touched.

For example, if one specific part inside a folder was touched I would use:

folder.part.Touched:Connect(
	function(touch)
		if touch.Parent:FindFirstChild("Humanoid") then
			print("part touched")
			Humanoid.Health = 0 
			wait(1)
		end
	end
)

But then I would have to rewrite this for every single part inside the folder, right?

So how would I avoid this?

You can use a for loop to loop through every part in the folder and apply the event

1 Like

function(touch) is creating an anonymous function, i.e. a function without a name.

Give it a name:

local function MyFunction(touch)
	if touch.Parent:FindFirstChild("Humanoid") then
		print("part touched")
		Humanoid.Health = 0 
		wait(1)
	end
end

Then use the name instead of the anonymous function:

folder.part.Touched:Connect(MyFunction)

Now it’s maybe easier to see how to loop through the children and connect them all:

for _, child in folder:GetChildren() do
  child.Touched:Connect(MyFunction)
end

I also recommend looking at CollectionService, specifically, the example at the bottom of that page. It’s a cleaner way to do things like this where you can put the parts anywhere in your hierarchy you wish.

Edit: I also wrote up something about the why/how of using CollectionService here:

3 Likes

you could use local parts = folder.part:GetTouchingParts()

GetTouchingParts gets everything that is currently touching the part.

and then you’d do something like this

if parts.Parent:FindFirstChild(“Humanoid”) then
print(“part touched”)
Humanoid.Health = 0
wait(1)
end

Hope this helped!

3 Likes