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

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

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.

1 comment

0

Don't you mean to table the items that are models? Also, you want to put their names in a table, correct?

1 answer

✓ Accepted answer

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.

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