I want to be able to fire an event if any parts in a table are touched, can this be done?
No, you would need to iterate over the table and attach to each individual Touched event:
for _,v in pairs(instances) do
v.Touched:Connect(functionGoesHere)
end
Is this correct?
local WaterWL = workspace.Water:GetChildren()
for _,v in pairs(WaterWL) do
v.Touched:Connect(function()
print("Water was touched")
end)
end
If it is, it doesnt seem to work.
That code is correct, so there must be something wrong with your instance setup then.
From an efficiency standpoint, does it make a difference if he repeats the whole function multiple times rather than stating the function once before the loop and referencing it in the connection?
Yes, a new closure wouldn’t be made every iteration and the function wouldn’t have access to the part that was touched, only the event arguments.
It depends on whether you need a closure or not (i.e. if there are variables inside the for-loop that you need to access, such as “v”). As far as I know it’s not too inefficient either way since you just get the variables in the closure as extra data, the whole function isn’t encoded multiple times in memory or anything I think.
It would probably be better to extract it as a separate function. But the poster seems like he first needs to understand the basics of what is happening.
In the way that you worded it explicitly, no you cannot - you must iterate over the objects and handle them individually. On the other hand though, you could do something like it. Tada, CollectionService. Write a handler for a specific tag (InstanceAdded and/or GetTagged). From there, just iterate over your objects and add the tag to them. Works like a charm so long as you account for tags right.
CollectionService:GetInstanceAddedSignal("WatchBrick"):Connect(function (AddedInstance)
-- stuff
end)
for index, value in ipairs(wherever) do
CollectionService:AddTag(value, "WatchBrick")
end