Trying to Count how Many Clones I've Put in a Folder, but it Doesn't Correctly Count

Hi! I’m cloning rings and putting them into the workspace folder, and I’m trying to have a limit to how many cloned rings can be at once in the folder. The limit for now is supposed to be 10, but for some reason the script stops cloning and putting rings into the workspace folder at 5 rings.

I tried solving the issue by printing the amount of rings inside the folder, but the counter is completely wrong.

Here is the code:

local ServerStorage = game:GetService("ServerStorage")
local interval = 5
local obj = script:WaitForChild("Ring")

local folder = workspace:FindFirstChild("Rings")

local count = 0
while count <= 10 do
	for i, v in pairs(workspace:WaitForChild("Rings"):GetChildren()) do
		if v.Name == "RingClone" then
			count += 1
		end
	end
	print(count)
	local clone = obj:Clone()
	clone.Name = "RingClone"
	clone.Parent = folder
	task.wait(interval)
end

This is print for the amount of rings in the folder from the output (For some reason it jumps from 1 to 3, then 6, and so on. While it is supposed to be counting by 1,2,3,4,5,6,7,8,9,10.):

image_2024-01-01_012602621

Then here is the RingFolder located in the workspace (The script stopped cloning the rings and putting into the folder at 5 rings):

image_2024-01-01_012658769

Can someone please explain and help me on this issue? Thanks.

1 Like

You are not resetting the count value on each loop, also why not just use #workspace:WaitForChild(“Rings”):GetChildren() to get the child count?

2 Likes

how do I reset the count value on each loop? like

local count = 0
while count <= 10 do
	for i, v in pairs(workspace:WaitForChild("Rings"):GetChildren()) do
		if v.Name == "RingClone" then
			count += 1
		end
	end
    count = count --Is this how you reset the count?
	print(count)
	local clone = obj:Clone()
	clone.Name = "RingClone"
	clone.Parent = folder
	task.wait(interval)
end
1 Like
local count = #workspace:WaitForChild("Rings"):GetChildren()
while count <= 10 do
	count += 1
	print(count)
	local clone = obj:Clone()
	clone.Name = "RingClone"
	clone.Parent = folder
	task.wait(interval)
end

Try this

2 Likes

Yeah it works, but do you know how to keep the loop going after reaching the limit and deleting some rings from the folder?

1 Like
workspace:WaitForChild("Rings").ChildRemoved:Connect(function()
local clone = obj:Clone()
	clone.Name = "RingClone"
	clone.Parent = folder
end)
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.