Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How can I get the #children with a specific name?

Asked by 5 years ago
Edited 5 years ago

So in a model, there is parts named "part1" and "part2". I want to only count the parts with a specific name.

This works but doesn't count the number of "part1". Instead it counts all parts with different names.

children = model:GetChildren()

for i = 1, #children do 
    if children[i].Name == "part1" then 
        print(#children)
    end
end
0
I tried print(#children[i]), returns a userdata error awesomeipod 607 — 5y

2 answers

Log in to vote
3
Answered by
nilVector 812 Moderation Voter
5 years ago

This is simply because you're printing the number of children in the model regardless of what you're checking in the loop. All you need is a simple variable that keeps track of the number of parts with the name "part1" and increment it every time you encounter one with such a name. For example:

local children = model:GetChildren()
local count = 0

for i = 1, #children do 
    if children[i].Name == "part1" then 
        count = count + 1
    end
end
print(count)

(additionally, it is recommended that you use local variables, because Lua works in such a manner to where local variables are indexed faster - it's just better practice in general too even if the performance is negligible)

Ad
Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

do this instead

for i, child in pairs(model:GetChildren()) do
    if child.Name == "part1" then
        print(child)
    end
end

This way it iterates through the actual children of the model instead of just an incremented int value

0
No, numerical for is slightly faster than generic for so his solution is quicker, the difference will be especially noticeable if you have many children. LifeInDevelopment 364 — 5y

Answer this question