Basically, I have several parts that do the same thing when a user touches them. I have always dealt with this by doing something like this:
local Parts = game:GetService("Workspace").DesiredModelContainingParts--This obviously will change depending on what the parts are for key,value in pairs(Parts:GetChildren()) do value.Touched:Connect(function(Hit) --do desired stuff end) end
I've used this style in studio with no problem, but I was wondering if it would work when multiple parts are being touched at the same time. I assume so because it should be the for loop should add a listener for each individual part. I prefer doing it this way because if I have a lot of parts performing the same function, it seems redundant to write the same function over and over.
Yeah, that will work with multiple parts as you are creating a new listener for every part, like you said. However, if you do not require any variables from the scope of the loop in the touch function, it may be slightly better to do something like this:
local function TouchFunc(Hit) --do desired stuff end for key, value in pairs(Parts:GetChildren()) do value.Touched:Connect(TouchFunc) end
This is because, instead of creating a new anonymous function for every part (potentially resulting in more memory usage), each part refers to the same single function. However, I do not know how much of a difference this really makes, and is probably insignificant in most cases. Also, in many cases you need to know what part was touched, which will require an anonymous function like you have used.
Hope this helps!