How would i update a value so that it corresponds to the number of basepart's in workspace if decreased

Greetings Developers,

The script below is a small portion of a larger script that spawns gold basepart’s every few seconds into the workspace and what i’m trying to achieve is so that if the amount of gold indexed in the workspace is equal or higher than 20 then it will stop spawning gold

I have managed to find a way to index parts if they were found in the workspace if the amount of gold was increasing but i’m stumped on how to update the value of “GoldWorkspaceCount” if the amount of gold found decreased

I could not find any solutions on the devforum or on youtube on what i’m trying to achieve so im posting this here

local GoldWorkspaceCount = 0

while task.wait(1) do
	for i, v in pairs(workspace:GetChildren()) do
		if v:IsA("BasePart") and v.Name == "Gold_Ore" then
			GoldWorkspaceCount += 1
		end
	end
end

Instance | Roblox Creator Documentation and Instance | Roblox Creator Documentation should help you out. In future, if you find that you end up using loops with no break condition, you’re doing something wrong and you’re probably missing out on a useful script signal.

local goldCount = 0
local workSpace = game.Workspace

workSpace.ChildAdded:Connect(function(child)
	if child.Name == "Gold" then --whatever name gold parts have
		goldCount += 1
	end
	print("There are "..goldCount.." pieces of gold.")
end)