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

How can I get a table of all items in a Model?

Asked by 10 years ago

I'm trying to make a welding script for a Model. There are Models inside the Models and even further, and I need to not use methodception (or at least try to avoid it) and get a table of all the children in all the models that aren't models. This is my code so far:

--what am i in?
v = script.Parent

--what to weld to
d = v.VehicleSeat

--weld script

local function weld(b)
    local weld = Instance.new("ManualWeld")
    weld.Part0 = d
    weld.Part1 = b
    weld.C0 = CFrame.new()
    weld.C1 = b.CFrame:inverse() * d.CFrame
    weld.Parent = d
    return weld;
end

--welding time
for k,o in pairs(v:GetChildren()) do
    if o:IsA("Model") then
        --this is where I want to do the code, but don't want repetion
    elseif o:IsA("BasePart") then
        weld(o)
    end
end

I've commented the code where I need to do the stuff.

0
Don't you mean to table the items that are models? Also, you want to put their names in a table, correct? Shawnyg 4330 — 10y

1 answer

Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

This is a simple application of recursion.


We call a Child, or a Child of a Child, or a Child of a Child (and so on) a descendant.

Observation: A descendant of m is either * a child, c, of m * or a descendant of c

This gives us a clear recursive model:

function getDescendants(m)
    local t = {}
    for _, c in pairs(m:GetChildren()) do
        table.insert(t, c)
        local desc = getDescendants(c) -- Recursion
        for _, d in pairs(desc) do
            table.insert(t, d)
        end
    end
    return t
end

Then, instead of v:GetChildren() we just use getDescendants(v) in your final loop, checking as normal that each descendant is in fact a BasePart.

Ad

Answer this question