Code is Counting Non-Existent Children in A Folder

I’m trying to make it so there’s a limit to how many coins can spawn (CoinSpawnLimit is set to 20 right now), which works completely fine. However, I also have a script that destroys the coin whenever I touch it, which should make it so that it’s no longer at the limit and can spawn a new one, but the code still thinks that there are 20 Instances in the Coin Folder and I don’t know why. Any help is appreciated!

This is the code that finds how many Children are in the folder:

while wait(1/CSRDivider) do
	if CoinLimitReached == false then
		ValueName = 0
		Coin = Instance.new("Part")
		x = math.random(22.552, 73.784)
		z = math.random(-49.377, -23.206)
		Coin.Name = "Coin"
		Coin.Parent = CoinFolder
		Coin.Size = Vector3.new(0.536, 0.557, 0.465)
		Coin.Position = Vector3.new(x, 2.24, z)
		Coin.Anchored = true
		Coin.CanCollide = false
		warn(#CoinFolder:GetDescendants())
		if #CoinFolder:GetDescendants() >= CoinSpawnLimit then
			CoinLimitReached = true
		else
			CoinLimitReached = false
		end
	end
end

I’m assuming you want to remove the child from the folder once it’s destroyed.

I’d iterate thru the folder (using a pairs loop) and checking for the coins name. Once I find the coin, I’d remove it from the folder (coin:Destroy()) THEN I’d destroy the actual coin (don’t destroy the coin before iterating).

Oh, and check if the coin limit is reached, if it is then set it to false (make sure to check it in the coin destruction script)

1 Like

Thanks, Had my Coin:Destroy() In a local script and switched it so now it’s working.

1 Like

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