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?
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: