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

Real quick question, how to get all children of an object?

I have a frame and inside that frame is lots of other frames and inside those frames are buttons.

I know its hard to describe.

But I dont want to define every button individually so I tried this line of code but for some reason its not working.. Can you not have a for loop inside another for loop?

Heres the code

function ButtonClicked()
	for i,Child in pairs(script.Parent:GetChildren()) do
		if Child:IsA("Frame") then
			for i,Child2 in pairs(Child:GetChildren()) do
				for i,Child3 in pairs(Child2:GetChildren()) do
					if Child3:IsA("ImageButton") then
						Child3.MouseButton1Click:Connect(function()
							print("Button Clicked")
						end)
					end
				end
			end
		end
	end 
end

I know its kinda messy but yeah, its not working so any ideas?

2 comments

0

It is hard but I know a messed up way

0

I remember doing this back when I didn’t know what :GetDescendants() was. Just do what Moo said.

1 answer

✓ Accepted answer

What you want is the function GetDescendants()

local myFirstFrame = Parent:WaitForChild("NameOfFrame")
local descendants = myFirstFrame:GetDescendants()

local function SetButtonListener()
	for _,descendant in pairs(descendants) do
		if descendant:IsA("ImageButton") then
			descendant.MouseButton1Click:Connect(function()
				print("ImageButton " .. descendant.Name .. " has been set")
			end)
		end
	end
end

SetButtonListener()

GetDescendants() returns a table. And for iterating through a table you would use a For loop. Then check if it's an ImageButton(like you have in your code) and set the event.

Edit:Wierd spacing showed up on my code

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