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

Why aren't my coins saving properly on my leaderboard?

Asked by
Soban06 410 Moderation Voter
4 years ago

So I am making an obby with a leader board which has 2 values: Coins and Checkpoints. Once a player touches a coin, it adds a coin to their leader board. Let's say a player has 4 coins, and then the player leaves the game and then if they join again, they still have 4 coins.

But if the player get's another coin, the coins increase from 4 to 5, but once they rejoin the game, they have 4 coins not 5.

Why is this so?

Here is the script which saves the leaderboard. It is located in ServerScriptService:

local DataStoreService = game:GetService("DataStoreService")
local myDataStore = DataStoreService:GetDataStore("myDataStore")


game.Players.PlayerAdded:Connect(function(player)
    local leaderstats = Instance.new("Folder", player)
    leaderstats.Name = "leaderstats"

    local Checkpoint = Instance.new("IntValue", leaderstats)
    Checkpoint.Name = "Checkpoint"
    Checkpoint.Value = 1

    local coins = Instance.new("IntValue", leaderstats)
    coins.Name = "Coins"
    coins.Value = 0

    --Checkpoint Section
    player.CharacterAdded:Connect(function(character)

        repeat wait() until player.character ~= nil
        local checkpoint = game.Workspace.Checkpoints:FindFirstChild(Checkpoint.Value)
        character:WaitForChild("HumanoidRootPart").CFrame = CFrame.new(checkpoint.Position + Vector3.new(0, 2, 0))

    end)

    -- Data Store Section

    local playerUserId = "Player_"..player.UserId
    print(playerUserId)

    -- Load Data

    local data
    local success, errormessage = pcall(function()
         data = myDataStore:GetAsync(playerUserId)

    end)


    if success then
        if data then
        coins.Value = data.Coins
        Checkpoint.Value = data.Checkpoint
        -- Set our data equal to the current Coins
        end
    end

end)

game.Players.PlayerRemoving:Connect(function(player)
    local playerUserId = "Player_"..player.UserId

    local data = {

    Coins = player.leaderstats.Coins.Value;
    Checkpoint = player.leaderstats.Checkpoint.Value;

    }

    local success, errormessage = pcall(function()
        myDataStore:SetAsync(playerUserId, data)
    end)

        if success then
            print("Data successfully saved!")
        else
            print("There was an error saving the data!")
            warn(errormessage)  
        end

end)

Please help me.

Thanks

Answer this question