Ok, so I basically want to search through everything inside of game for an object named "CorrectModel." I have an idea of how to do this:
for i,v in pairs(game:GetChildren()) do for i,v in pairs(v:GetChildren()) do for i,v in pairs(v:GetChildren()) do for i,v in pairs(v:GetChildren()) do -- Am I right? end end end end
Is this correct? If so, what else should I do?
Thanks!!
You shouldn't nest for
loops "deep enough".
If you had 12 nested loops, it's possible the model you're looking for is 13 deep.
You want to actually search the whole tree, which can be done recursively.
Luckily, :FindFirstChild
can already search for names recursively.
local model = workspace:FindFirstChild("CorrectModel", true)
This will find model
no matter where it's nested inside of workspace
.
To manually write this code yourself, you need to write a recursive function:
function search(model) -- if you give it what you're looking for, you're done! if model.Name == "CorrectModel" then return model end -- Otherwise, you have to search through its children for _, child in pairs(model:GetChildren()) do local foundInChild = search(child) if foundInChild then return foundInChild end end end local model = search(workspace)