Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I use the number of children of an object to determine when a script is executed?

What I have is a folder in the workspace named CoinStorage and a Coin which is stored in ServerStorage. Every second, a coin is spawned into the workspace, in a folder named CoinStorageMain and the script is setup so that it should stop executing when the number of coins in CoinStorageMain is above 10 however this doesn't happen. The script keeps executing no matter how many coins there are and I don't know what else to try.

This code is in a script in ServerScriptService.

local coinsInStorage = workspace.Main.CoinStorageMain:GetChildren();
local coinModel = game:GetService("ServerStorage"):WaitForChild("CoinStorage"):WaitForChild("Coin")

while true do
	if (#coinsInStorage <= 10) == true then
		local copy = coinModel:Clone()
		copy.Parent = workspace.Main.CoinStorageMain
		copy.CFrame = CFrame.new(math.random(-31.5, 17.5), 1.5, math.random(-17.5, 28.5))
		wait(1)
	else
		return nil
	end
end

1 comment

1

The "== true" part is not necessary, so remove that. You are also only getting all the coins once. Try putting "coinsInStorage" inside the loop so it can update.

2 answers

✓ Accepted answer

Looks like the issue is that you're checking CoinStorage once and only once at the beginning of the script, when there is nothing inside of it. Good thing is theres an easy solution to this, which is to just move this variable inside of the loop.

local coinModel = game:GetService("ServerStorage"):WaitForChild("CoinStorage"):WaitForChild("Coin")

while wait() do
    local coinsInStorage = workspace.Main.CoinStorageMain:GetChildren()
	
    if (#coinsInStorage <= 10) == true then
        local copy = coinModel:Clone()
        copy.Parent = workspace.Main.CoinStorageMain
        copy.CFrame = CFrame.new(math.random(-31.5, 17.5), 1.5, math.random(-17.5, 28.5))
        wait(.1)
    else
        return nil
    end
end

Credit to Denny9876

I moved the local which determines the number of coins in storage into the loop and deleted the == true part and it works. Thanks for the response!

New code:

local coinModel = game:GetService("ServerStorage"):WaitForChild("CoinStorage"):WaitForChild("Coin")

while true do
	local coinsInStorage = workspace.Main.CoinStorageMain:GetChildren();
	if (#coinsInStorage < 10) then
		local copy = coinModel:Clone()
		copy.Parent = workspace.Main.CoinStorageMain
		copy.CFrame = CFrame.new(math.random(-31.5, 17.5), 1.5, math.random(-17.5, 28.5))
		wait(1)
	else
		return nil
	end
end

This discussion is preserved as it was. New answers, comments, and votes are closed.