Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

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

Asked by 5 years ago

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
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. User#20279 0 — 5y

2 answers

Log in to vote
1
Answered by
BuDeep 214 Moderation Voter
5 years ago

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
Ad
Log in to vote
0
Answered by 5 years ago

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

Answer this question