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.
1 | children = model:GetChildren() |
2 |
3 | for i = 1 , #children do |
4 | if children [ i ] .Name = = "part1" then |
5 | print (#children) |
6 | end |
7 | 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:
1 | local children = model:GetChildren() |
2 | local count = 0 |
3 |
4 | for i = 1 , #children do |
5 | if children [ i ] .Name = = "part1" then |
6 | count = count + 1 |
7 | end |
8 | end |
9 | 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
1 | for i, child in pairs (model:GetChildren()) do |
2 | if child.Name = = "part1" then |
3 | print (child) |
4 | end |
5 | end |
This way it iterates through the actual children of the model instead of just an incremented int value