Is there any way to get the children from a Folder and connect them to a function?

consider the following script:

local t = {workspace.tp:GetChildren()}
t.Touched:Connect(function(TouchedPart,Hit)
	print(TouchedPart)
	print(Hit)
end)

my idea was to get all the children out of a folder so I don’t have to repeat them
I would also like to know which part was played, in addition to Hit (who touched it)

The problem is that the script doesn’t work( [attempt to index nil with ‘Connect’])
I have a print of this folder:
dasdasdasdsa

is there any way to do this?

3 Likes

You can do:

for i, v in pairs(t) do
    v.Touched:Connect(function()
    
    end)
end
1 Like

there was the following error: [attempt to index nil with ‘Connect’]
apparently, the script understands that “v” is the Table.
Print (v) → table: 0x901ff18aa29d9525

I think it actually printed an memory data inside the table.

I did the following:

local t = {workspace.tp:GetChildren()}
for i,v in pairs (t) do
	for a,b in pairs (v) do
	b.Touched:Connect(function(Hit)
		
		print(Hit)
	end)
	end
end

it works, but is it really right to do like this?

local t = workspace.tp:GetChildren()

for i, v in ipairs(t) do
	v.Touched:Connect(function(hit)
		print(hit)
	end)
end

Try the code above.

1 Like
for i,v in pairs(workspace.tp:GetChildren()) do
     if v:IsA('BasePart') then
         v.Touched:Connect(function(Hit)
              print(Hit.Name)
         end)
    end
end

Casually spoonfeeds.

1 Like

Uh, technically, you don’t need to use print(Hit.Name), print(Hit) would do the same thing.

Answer: Yes.

2 Likes

I understand that, but that’s pretty irrelevant to the proposed problem, right?

2 Likes

Did you test the code we provided?

1 Like

this worked, but what is the difference from “ipairs” to “in pairs”?

https://devforum.roblox.com/t/pairs-vs-ipairs-vs-next/21837

I just used ipairs cause of the reply that is marked as solved.

1 Like

ipairs is usually used in numeric tables where pairs isn’t as much. Though in my testing, using pairs normally works best for me but in cases where you want it to stop if it finds a nil value, use ipairs.

1 Like

is there any chance of a nil Value appearing in my table? (without me putting)

Just read. [30 charsssssssssss]

1 Like

I’d like to add that in the OP you were declaring the table as t = {workspace.tp:GetChildren()} .

This is flawed in itself, as the :GetChildren() function returns a table. So, basically, you were putting that table inside another table by calling it as {workspace.tp:GetChildren()}

2 Likes

I doubt it. GetChildren() returns an array, I believe, so ipairs will work better for that, but otherwise use pairs.

1 Like