Hello, I am working on something that continues to spawn bricks until it reaches a certain amount but I also want it to continue doing if it goes under 10 again. (Like if it’s at 10 parts and I delete 1 it should start adding another part.) Now how would I do that?
The code below is what I was suggested before hand which works- until you try do remove a part and you realize that it doesn’t loop again.
while #game.Workspace.Folder:GetChildren() < 10 do --the number used is an example
end
You can detect when the part is deleted/destroyed using Instance | Documentation - Roblox Creator Hub from the folder the part is stored. From there you can start the while loop again.
I don’t recommend @MixedConscience polling approach as every wait() you are potentially doing an unnecessary :GetChildren() operation when potentially no parts have been removed from the folder at all.
local Folder = workspace.Folder
Folder.ChildRemoved:Connect(function()
local Children = Folder:GetChildren()
local connection = game:GetService("RunService").Heartbeat:Connect(function()
if (#Children < 10) then
--add part
print("Added")
elseif (#Children == 10)
connection:Disconnect()
print("Disconnected")
end
end
end)
Would be better than a while loop. And I’m unsure about Runservice.Heartbeat because it’s deprecated. If that doesn’t work might be the event so use RunService.PostSimulation instead or if it errors come back.
Make sure to remove the part from the server to ensure the script can detect the parts properly destroying.
Anyways for @MixedConscience you can still use a while loop and its easier since you don’t have to manage the connection but yeah just make sure to avoid stack overflow error like I did .
Full code + Explosions
local partFolder = Instance.new("Folder")
partFolder.Parent = workspace
local function randomVector(xmin,xmax,ymin,ymax,zmin,zmax)
return Vector3.new(math.random(xmin,xmax),math.random(ymin,ymax),math.random(zmin,zmax))
end
local function spawnParts(folder)
local children = folder:GetChildren()
local numChildren = #children
while numChildren < 10 do
local part = Instance.new("Part")
part.Position = randomVector(-5,5,0,5,-5,5)*10
part.Parent = folder
local explosion = Instance.new("Explosion")
explosion.BlastPressure = 500000 * 10
explosion.Position = part.Position+randomVector(-5,5,-5,5,-5,5)/5
explosion.Parent = workspace
local children = folder:GetChildren()
numChildren = #children -- make sure to remeasure or else..
end
end
partFolder.ChildRemoved:Connect(function()
spawnParts(partFolder)
end)
spawnParts(partFolder)