-- Collect-All-Coins: coin manager.
-- Goes in a Script in ServerScriptService. Wires up every coin inside a
-- Folder named "Coins" in Workspace, and announces a win when the last
-- coin is collected.
local Players = game:GetService("Players")

local coinsFolder = workspace:WaitForChild("Coins")
local total = #coinsFolder:GetChildren()
local collected = 0

for _, coin in ipairs(coinsFolder:GetChildren()) do
    coin.Touched:Connect(function(otherPart)
        -- if this coin is already gone, ignore the touch
        if coin.Parent == nil then
            return
        end

        local player = Players:GetPlayerFromCharacter(otherPart.Parent)
        if player == nil then
            return
        end

        local leaderstats = player:FindFirstChild("leaderstats")
        if leaderstats then
            local score = leaderstats:FindFirstChild("Coins")
            if score then
                score.Value = score.Value + 1
            end
        end

        coin:Destroy()
        collected = collected + 1

        if collected >= total then
            print(player.Name .. " collected all the coins! You win!")
        end
    end)
end
