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
local folder=workspace:WaitForChild("insertfoldername")
local part=folder:WaitForChild("insertpartname")
task.spawn(function()
while true do
task.wait(2)
local partClone=part:Clone()
partClone.Parent=folder
if #folder:GetChildren()>=100 then
--put code here
break
end
end
end)
While these solutions could work, using a loop to check when a child is gone is not optimal.
Try using signals where possible to minimize how much the code runs.
local spawning = false
local queue = false
local function spawnParts()
if spawning then
queued = true
return
end
spawning = true
local children = partsParent:GetChildren()
local targetCount = 100
for i = 1, targetCount - #children do
-- spawn things
task.wait(2)
end
spawning = false
if queued then
queued = false
spawnParts()
end
end
partsParent.ChildRemoved:Connect(spawnParts)
spawnParts()
1 Like