How To Add Spawn Cap To Spawn System

Hello! I made a script which spawns in Candy that the player can collect, however I feel that to avoid too many spawning there should be a cap to how many there can be at one time. However, since I am still pretty new to scripting I need some help. How could I add this system to my script? When the Candy is spawned, it is placed inside a folder called “CandyG” and I thought the children of this folder could be counted and that is possibly how it could function? Anyways tell me your ideas.

local coin = game.Workspace.CandyPart
local counter = 0
local CandyCap = 250 --The max amount of Candy that can spawn

function SpawnCandy()
	local newcoin = coin:Clone()
	newcoin.Parent = game.Workspace.CandyG
	newcoin.Position = Vector3.new(math.random(-138, 125.895), 5.268, math.random(21.053, 286.874))
end


while true do
	if counter > 120 then --This spams candy at the start of the game so when a player joins an empty server there is still a good amount of candy
		wait(math.random(0.2,0.5))
	else
		wait()
	end
	counter += 1
	SpawnCandy()
end
if #workspace.CandyG:GetChildren() < CandyCap then
    SpawnCandy()
end
2 Likes

Thanks I knew it was pretty simple

Just in case anyone reads through this thread in the future and wonders how the solution works, here’s a quick explanation:

  • Calling :GetChildren() on an object like a Part, Model, Folder, etc. will create a table that contains all the objects that were directly placed into it (so if you place a Model into a Folder, but that Model has multiple parts in it, the Folder:GetChildren() call would only directly retrieve the Model).

  • The # is an operator that can be used to check the length of a table / how many values are in the table.

    • As a result, when you use the # operator on the workspace.CandyG:GetChildren() call, it returns a number that tells you how many objects are in the folder (on the first layer).

      • That number can be compared to the “CandyCap” that was defined at the top of the script, so that if the number of objects in the “CandyG” folder is less than maximum limit defined by the “CandyCap” variable (which in this case, is 250), it will call the “SpawnCandy” function to spawn another Candy, placing it into the folder.

        If the number of objects is greater than the maximum limit, then the conditional statement will be false, meaning that the “SpawnCandy” function will not be called again until the total number of objects in the “CandyG” folder is less than the limit.

3 Likes

I wish I could put 2 solutions ;(

1 Like

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