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
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)
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