My for i,v loop doesnt work

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!

For someone to help me fix the loop

  1. What is the issue? Include screenshots / videos if possible!

I need help with my for i, v loop

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

Since I am new to scripting I have watched tutorials to understand the loop but I couldnt find anything close to my problem

for i, v in pairs(script.Parent.Coins:GetChildren()) do
	if v.Name == "PrimaryPart" then
		if i == 5 then
			v:Destroy()
		end
	end
end

Also if you could give me some information what I did wrong would be appreciated.

Use ipairs because pairs are not used for array (normal) tables now, use pairs when you iterate through dictionaries

for i, v in ipairs(script.Parent.Coins:GetChildren()) do
	if v.Name == "PrimaryPart" then
		if i == 5 then
			v:Destroy()
		end
	end
end

The coins spawner is still spawning more than 5, also whats the difference between in ipairs and in pairs

I edited my previous message but if you still don’t understand read this

Then try it:

local nb = 0

for i, v in ipairs(script.Parent.Coins:GetChildren()) do
    local nb  += 1
	if v.Name == "PrimaryPart" then
		if nb == 5 then
			v:Destroy()
		end
	end
end

You have two local variables do i need to use both?

No you don’t need you can second one change to global if you want

Are the coins being spawned in a separate folder than the rest of the games objects?

Yes they are. Sorry for the late reply

What code generates the coins? I would simply add a check before spawning:

if #coinsFolder:GetChildren() < 5 then

end
1 Like