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)
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)