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 https://developer.roblox.com/en-us/api-reference/class/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:
CollectionService is just a way to maintain sets of Instances. It is sort of like a folder, but more useful, and probably more efficient.
Benefits
Checking if a specific Instance is in a Collection, for example, is going to be quicker than looping through all the children of a folder to check if that Instance is a child.
It also lets you separate “where an object is” from “what an object is” – if you had a Tag that meant “this part can kill people who touch it”, you can throw those parts wher…
4 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!
2 Likes