Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Touched Event with :GetChildren()?

So basically instead of pasting a script with the

function onTouched(hit)
print(script.Parent.Name.. " was touched!")
end

script.Parent.Touched:connect(onTouched)

I was wondering if there was a way to do something like:

Model:GetChildren().Touched:connect(onTouched)

or something of the sort, but it would still work the same rather than having every block in the model reacting, just the block that was touched.

3 comments

0

So are you wanting an efficient way to add a touched event to multiple parts without repeating code?

0

Yes

2

Iterate through the table returned by :GetChildren with a for loop and then connect the event to each returned part. Unless hit detection has to be super accurate, I would suggest just welding a part that just about the size of the model, and listening to the Touched event for that welded part.

1 answer

✓ Accepted answer

In order to achieve what you're aiming for, you're going to need to put the GetChildren function in a for loop. That for loop would then have to iterate through all parts connecting each part with the Touched event.

for _,Part in pairs(Model:GetChildren()) do --So for every index and value the loop will do something with that value variable which in this case is the Part.
    Part.Touched:connect(function(Hit) --This is setting up an anonymous function which will execute once the Touched event is fired.
        print(Hit.Name) --Will print the object that hit "Part".
    end)
end

This discussion is preserved as it was. New answers, comments, and votes are closed.