I was bored, so I decided to make a Part scanner script, and I did this test, instead of using + 1
for counting the parts, I tested + i
and it printed out 183789
, why and how did it get that many? o_e Here is the script;
local numParts = 0 local function partScan(part) for i,v in pairs(part:GetChildren()) do pcall(function() local testName = v.Name end) if v:IsA("Part") then numParts = numParts + i --This is the line that I used 'i' instead of '1' end partScan(v) end end partScan(game.Workspace) print(numParts)
Well, if you add i, you're adding the index of that specific table of children. Let's say the hierarchy looks like this (pretend it makes logical sense; the parenthesis and numbers is the number actually added to your variable):
Part (+1) Part (+1) Part (+2) Part (+1) Part (+2) Part (+3) Part (+3) Part (+4) Part (+1) Part (+2) Part (+1) Part (+5)
Basically doing your function is like doing this:
1 + 1 + 2 + 1 + 2 + 3 + 3 + 4 + 1 + 2 + 1 + 5
, which equals 26, which clearly there are actually only 12.
Now, let's look at what happens if it doesn't find a "Part" like your code looks for, assuming this is the exact order it searches the children in:
Part (+1) Part (+1) Model -- Not a part, so it's not adding it. Part (+3) Part (+1) Part (+2) Model Part (+4) Part (+4) Part (+5) Part (+1) Model Part (+3) Model Part (+2) Part (+6)
Basically doing your function is like doing this:
1 + 1 + 3 + 1 + 2 + 4 + 4 + 5 + 1 + 3 + 2 + 6
, which equals 33, which clearly there are actually 12 parts, still.
Conclusion: So, just stick with + 1
instead of + i
to make a part counter to get the correct count.
Hint: If you want to get parts, use :isA("BasePart")
instead of :isA("Part")
because ALL types of bricks are BasePart
.