Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

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

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

1 comment

0

I tried print(#children[i]), returns a userdata error

2 answers

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

1 comment

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.