Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 6 years ago

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?

0
It is hard but I know a messed up way greatneil80 2647 — 6y
0
I remember doing this back when I didn’t know what :GetDescendants() was. Just do what Moo said. User#20279 0 — 6y

1 answer

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

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

Ad

Answer this question