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.
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
.