Repeating something until a number is reached

I have a spawner that creates a part instance and puts it into a folder.
How would I make it so that the spawner keeps spawning a part every 2 seconds until there is 100 parts?

How would I make the script also count the parts in the folder so that if any parts are destroyed, it would start creating parts again until the 100 part limit is hit?

I have tried using the repeat until loops and while loops, but seem to get lots of errors, and cannot figure out the best way to do this without using things like while true do loops etc.

I was thinking of a for loop:

local PartAmount = #PartFolder:GetChildren()
for i = 1, 100 - PartAmount do
 task.wait(2)
— ceate instance here
end
2 Likes

that works great at first when the server starts, but how would I go about making it so that if the part count changes, it creates parts again until reaching 100?

I assume something like this:

local PartFolder = Instance.new("Folder")
PartFolder.Name = "PartFolder"
PartFolder.Parent = game.Workspace
	
while task.wait(2) do
	for i = 1, 100 - #PartFolder:GetChildren() do
		if i ~= 100 then
			--create instance here
            local part = instance.new("Part")
            part.Parent = partFolder
		end
	end
end

I changed the code a little bit. Correct me if I am wrong.

We can make a while loop, and check every 2 seconds, like you asked, if there are a 100 parts, if not, then create a new one.

Script (sorry made this on mobile):

while true do
local PartAmount = #PartFolder:GetChildren()
if PartAmount < 100 then
--create instance here
end
task.wait(2)
end
1 Like
local partFolder = instance.new("Folder")
partFolder.Name = "PartFolder"
partFolder.Parent = game.workspace

local function check() 
  parts = game.workspace:getChildren()
  

  for i = 1,100 do

    if #parts >= 100 then
       continue
    else
      local part = instance.new("Part")
      part.Parent = partFolder
    end

  end
end

while true do
  wait(1)
  check()
end