Can't set a maximum amount of parts that can spawn in a place

im making a system where coins spawn in a desert to collect

to reduce lag, i want to set a maximum amount of coins that can spawn inside the desert part, my method of doing this is getting the children of desert (where the coins are placed) and check if the amount of children are 5, and if it is then destroy the coin we just placed

local spawns = workspace.CoinSpawns
local coin = game.ReplicatedStorage.Coin

local desert = spawns.Desert
local desertcount = desert:GetChildren()

while true do
	wait(1)

	local coinclone = coin:Clone()
	
	
	-- desert
	
	coinclone.Parent = desert
	coinclone.CFrame = CFrame.new(
		desert.CFrame.X + math.random(-desert.Size.X/2,desert.Size.X/2)
		,desert.CFrame.Y+1,
		desert.CFrame.Z + math.random(-desert.Size.Z/2,desert.Size.Z/2)
	)
	coinclone.Spin.Disabled = false
	print("newcoin")
	if #desertcount == 5 then
		coinclone:Destroy()
		print("coindestroyed")
	end
	
	
	-- smt
	
	
end

the script doesnt print any errors but for some reason it keeps spawning the coins in no matter what i try to change

local spawns = workspace.CoinSpawns
local coin = game.ReplicatedStorage.Coin

local desert = spawns.Desert
local MaxCoins = 5 -- Max amount of Coins

while true do
	if #desert:GetChildren() < MaxCoins then
		local coinclone = coin:Clone()
		coinclone.Parent = desert
		coinclone.CFrame = CFrame.new(
			desert.CFrame.X + math.random(-desert.Size.X/2,desert.Size.X/2)
			,desert.CFrame.Y+1,
			desert.CFrame.Z + math.random(-desert.Size.Z/2,desert.Size.Z/2)
		)
		coinclone.Spin.Disabled = false
		print("newcoin")
	else 
		repeat wait() until #desert:GetChildren() < MaxCoins -- Wait until we can spawn coin again
	end
	wait(1) -- Wait to Prevent Lag
end

The reason your script was not working was

You were counting the amount of coins BEFORE you start spawning the coins.
to fix it, you needed to count the amount of coins inside the while true do loop

The fixed script, Possibly better version of your script,
i have listed above

1 Like