So I am wondering if there is a better way of doing this for loop?
for _,Ex in pairs(workspace:GetDescendants()) do
if Condition then -- Finds a Part under a Condition
end
if AnotherCondition then -- Finds a Part under another Condition, not similar to First
end
end
Although this is the right way to do it, it gets a bit messy and annoying to look for specific Parts, is there a better way of doing this?
You can assign parts a different tags, then you can use collectionService to later on, to get all parts with that tag, and do something to it.
If you mean that your for-loop the right way of doing something, then you really gotta specify what your goal is. You should always try to narrow down the stuff you would loop through.
if you can, placing them in a folder would help or referencing them in a table. Other than that I don’t think there is a way to get a bunch of parts without a for loop. Might be wrong though
I agree with @TortenSkjold and @4vI7 . Using CollectionService is a good method to get shorter tables to perform the loop, and using folders correctly is very helpful too.
Doing a loop from game.Workspace:GetDescendants() sounds like a very bad idea to me…
Could be thousands of Instances there… what would be the point on doing that just to give functions to specific parts if you can just iterate from folders and CollectionService?
Your code is already both clean and efficient. If you favor this style over performance though, it might help organize your script depending on how many times or ways you need to collect parts.
local function collect_with_condition(condition)
local result = {}
for _, obj in workspace:GetDescendants() do
local a,b = pcall(condition, obj)
if a and b then
table.insert(result, obj)
end
end
return result
end
local red_parts = collect_with_condition(
function(obj) return obj.BrickColor == BrickColor.new("Bright red") end
)
for _, obj in red_parts do print(obj) end
Yea, you’re already doing a loop, and I’m just telling you what you asked for, if there is a better way - No, the way you’re doing it would be the best, if you did not use :GetDescendants() on the whole workspace Instead you should create folders with the specific parts, and go through them instead.