I was wondering if there was a way to find all parts, regardless if they are in models or not. I know you can do this:
local Model = nil for i, v in pairs(Workspace:GetChildren()) do if v:IsA("BasePart") then print(v.Name) elseif v:IsA("Model") then Model = v for i, v in pairs(Model:GetChildren()) do if v:IsA("BasePart") then print(v.Name) elseif v:Isa("Model") then --and so on and so forth end end end end
I just want to know if there is a simpler way to do this.
Yes, there is - and it's also a very powerful concept to learn when it comes to programming and Computer Science.
It's called Recursion
Here's an example that matches your question, though, it prints all the
Part Instances of the
Instance that you send to the function.
function PrintParts(instance) if instance:IsA("BasePart") then print(instance.Name) end for _,child in pairs(instance:GetChildren()) do PrintParts(child) end end --Print all the parts in workspace PrintParts(workspace) --Print all the parts in Lighting PrintParts(game.Lighting)
Use functions for extra boost!
function Find(part) for i, v in pairs(part:GetChilren()) do if v:IsA"BasePart" then print(v.Name) end Find(v) -- is this madness? end end Find(Workspace)
This is a very simple, yet complex search technique! When you call
function Find and declare where it should start (etc. Workspace), it will search through children of
part and if the children is/are "BasePart", it will print its/their name. But, if it's not a "BasePart", it calls
function Find resulting in searching everything until there is nothing to search.
If you're only into searching Models, then just change
elseif v:IsA"Model" then.