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

Accurate Workspace Coin Counter Problems, anyone can help?

Asked by 2 years ago

I have coins that spawn randomly into the map. The coins have a script inside them that automatically despawns them after a random amount of time.

I have a separate script that is attempting to accurately keep track of the amount of coins in workspace through all the spawning and despawning and I'm at a loss at how to do this. The script is supposed to take this amount and put it into a number value.

I know what I have doesn't work but I'm not experienced in this kind of thing so any help would be appreciated. It does count coins but the numbers are way off.

coinsadded = 0
coinsremoved = 0
function AddCoinAmt() wait()
for _,v in pairs(workspace:GetDescendants()) do
    if v:IsA("Part") and v.Name == "CoinPart" then
            coinsadded = coinsadded + 1
        end
    end
    local coinvalue = script:FindFirstChild('CoinVal')
    if coinvalue then coinvalue.Value = coinsadded - coinsremoved
        end
end

function SubtractCoinAmt() wait()
    for _,v in pairs(workspace:GetDescendants()) do
        if v:IsA("Part") and v.Name == "CoinPart" then
            coinsremoved = coinsremoved + 1
        end
    end
    local coinvalue = script:FindFirstChild('CoinVal')
    if coinvalue then coinvalue.Value = coinsadded - coinsremoved
    end
end

workspace.ChildAdded:connect(AddCoinAmt)
workspace.ChildRemoved:Connect(SubtractCoinAmt)

1 answer

Log in to vote
1
Answered by 2 years ago

If you want to just store the amount of coins currently in the workspace, you can try this:

local coins = 0

game.Workspace.ChildAdded:Connect(function(child)
    if child:IsA("Part") and child.Name == "CoinPart" then
        coins += 1
    end

end)


game.Workspace.ChildRemoved:Connect(function(child)
    if child:IsA("Part") and child.Name == "CoinPart" then
        coins -= 1
    end
end)


If you want to be able to access the amount of coins from anywhere, you can add an IntValue to replicated storage and name it whatever you like. I'll name it "coins" for this demonstration

local coins = game.ReplicatedStorage.coins

game.Workspace.ChildAdded:Connect(function(child)
    if child:IsA("Part") and child.Name == "CoinPart" then
        coins.Value += 1
    end

end)


game.Workspace.ChildRemoved:Connect(function(child)
    if child:IsA("Part") and child.Name == "CoinPart" then
        coins.Value -= 1
    end
end)
0
I'm curious why you are using += and -= instead of just + or -? Either way this is still helpful so thank you very much UnderWorldOnline 59 — 2y
0
I'm curious why you are using += and -= instead of just + or -? Either way this is still helpful so thank you very much UnderWorldOnline 59 — 2y
0
its a shortcut for saying variable = variable - 1 or variable = variable + 1 sata5pa3da 286 — 2y
Ad

Answer this question