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

How would I get the children of the children I got?

Asked by 8 years ago

I know it sounds weird, and perhaps a little wrong, but you understand, right? ..right? If you don't, here is a full explanation. Ok, so I got the children of people, now for each child (of people) I want to scan them individually for a part called "torso"

So in other words,

I want to get the children(people's children) of the children that I got(the people). Get it now? Here's the script.

for _,v in pairs(workspace.People:GetChildren())do
    for _,w in pairs(v:GetChildren())do
        if w.Name=="Torso"then
        nodes[#nodes+1]=w
        end
    end
end

2 answers

Log in to vote
1
Answered by
DevChris 235 Moderation Voter
8 years ago

Just do another for loop inside it. This will cycle through the children you already got, and then cycle through their children.

for _,v in pairs(workspace.People:GetChildren())do
    for _,w in pairs(v:GetChildren())do
        for _,z in pairs(w:GetChildren()) do
            if z.Name=="Torso"then
                nodes[#nodes+1]=z
            end
        end
    end
end
Ad
Log in to vote
0
Answered by 8 years ago

What you need is recursion.

The short answer is to have a function and call the function from inside it, like so:

local allParts = {}

function recurringSearch(parent)
    for i, v in pairs(parent:GetChildren()) do --all the parents children
        if v:IsA("BasePart") then --if some kind of part
            table.insert(allParts, v) --put it in the table
        end
        recurringSearch(v) --run the function with the current objects children
    end
end

recurringSearch(workspace) --start the function and feed it workspace

This code fills up the table allParts with every part in workspace. This works no matter how many "parents" an object has.

So in your case:

function recur( parent )
    for _,v in pairs( parent:GetChildren() )do
        if v.Name == "Torso" then
            nodes[ #nodes+1 ] = v
        end
    end
end

recur( workspace.People )

Answer this question