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

Is it possible to listen for the touched event from multiple parts in a table?

So I have about 24 parts and they will all have their own function when they are touched. Instead of writing out 24 lines of

part1.Touched:connect(function..... end)
part2.Touched:connect(function..... end)
part3.Touched:connect(function..... end)

is it possible to have a table such as

parts = {part1, part2, part3}

And then have a function such as

parts:GetChildren().Touched:connect(function(child, part)... end)"

Because obviously I'd want to know what part was touched, and what touched it.

This is all in a server script, and I'm also not sure if it'd function properly with multiple players on a server because I haven't scripted in about 2 years, I forgot... So if 8 people were on the server would they all use the same 1 script and mess up the variables? Or would it replicate and run 8 times individually for each player? Thanks!

Tom

2 comments

0

This is certainly possible, but it might not be any better if you want each part to do a different thing when touched.

0

I actually want every part to start or stop a timer depending on variables when it was touched, but I am really lazy and I couldn't be bothered to make a smart script. How would I go about doing it in more detail?

1 answer

✓ Accepted answer

You would loop through all the parts and set up an event for it

To do this, it's probably easiest if we use a Generic For Loop. What this does, is it loops through a table, getting the values one at a time.

Example

local values = {
	"Hat";
	"Cat";
	"Rat";
	"Lion"
}

for i,v in pairs(values) do
	print(v)
end
This will print all the values in "values" one at a time.

Applying this to your problem

So, once we get a table of parts with the :GetChildren() function we then can loop through it with a generic for loop and add the touched event and function to each part, one at a time.

local parts = workspace.Folder:GetChildren()

for i,v in pairs(parts) do
	v.Touched:connect(function(p)
		print("I was touched by "..p.Name)
	end)
end

Good Luck!

If I helped, please don't forget to accept my answer.

5 comments

2

I approve this answer, but the only problem I have is that "Lion" doesn't rhyme with the rest in that table.

0

It doesn't?

1

I would have upvoted if they all rhymed >:(

0

Very useful, I wasn't sure that looping through a table and waiting for an event would work. In my mind what would happen is it would get to the first brick in the table and then wait until it was touched before continuing to the next brick, but thanks!

0

You guys think Lion is the misfit, when in reality Hat is. Thanks for accepting and liking my answer love.

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