I am currently trying to create a for loop that will get all of the children of a folder, determine if the children are the correct child type, and then do stuff with that. I have 2 for loops (because you can’t have a for loop run inside of a for loop, right?) and I am trying to access the variables from the first one to the second one.
My code so far
for _, ObjectCategory in pairs(path:GetChildren()) do
if ObjectCategory:IsA("Folder") then
-- Do stuff
end
end
for _, Objectin pairs(ObjectCategory:GetChildren()) do
if Object:IsA("Model") then
-- Do Stuff
end
end
for _, ObjectCategory in pairs(path:GetChildren()) do
if ObjectCategory:IsA("Folder") then
for _, Object in pairs(ObjectCategory:GetChildren()) do
if Object:IsA("Model") then
-- Do Stuff
end
end
end
end
For clarity, when looping through each ObjectCategory, the code will also loop through all Object in that ObjectCategory before iterating over the next item (ObjectCategory) in the list.
local tempTable = {} --create a table to hold all the folders
for _, ObjectVehicle in pairs(path:GetChildren()) do
if ObjectCategory:IsA("Folder") then
table.insert(tempTable, ObjectCategory)
end
end
for _, Objectin pairs(tempTable) do
if Object:IsA("Model") then --This will always return false tho
-- do stuff here
end
end
An alternative approach is to iterate through the descendants of an instance to a depth, d.
local recursion_depth: number = 2
local iterable: Instance = game.Workspace.Folder
local models = {}
function find_models(iter: Instance)
if d > depth then return end
depth += 1
for k, v in pairs(iter:GetChildren()) do
if v:IsA("Folder") then
find_models()
continue
end
if v:IsA("Model") then
table.insert(models, v)
end
end
find_models(iterable)