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

My DataStore isn't saving leaderstats?

Asked by 4 years ago

Hi. I'm trying to make a data store that saves the amount of cash someone has. But the problem is that it isn't saving. Here is the code.

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


function playerJoin(player)
    local leaderstats = Instance.new("Folder")
    leaderstats.Name = "leaderstats"
    leaderstats.Parent = player
    local Cash = Instance.new("IntValue")
    Cash.Name = "Cash"
    Cash.Value = 0
    Cash.Parent = leaderstats

    local playerUserId = "Player_"..player.UserId
    --Load Data
    local data
    local success, errormessage = pcall(function()
        local data = myDataStore:GetAsync(playerUserId)
    end)

    if success then
        Cash.Value = data
        -- Set our data to the current Money

    end


end

game.Players.PlayerRemoving:Connect(function(player)
    local playerUserId = "Player_"..player.UserId
    local data = player.leaderstats.Cash.Value
    local success, errormessage = pcall(function()
    myDataStore:SetAsync(playerUserId, data)    
    end)
    if success then
        print("Data Succesfully Saved!")
    else
        print("There was an error when saving data!")
        warn(errormessage)
    end
end)

game.Players.PlayerAdded:Connect(playerJoin)
0
Put print statements to debug it. kingblaze_1000 359 — 4y

1 answer

Log in to vote
0
Answered by 4 years ago

When using Players.PlayerRemoving event, it doesn't save the last player in the server, the reason why is because the server instantly shuts down when the last player leaves. A way to solve that is use game:BindToClose(). game:BindToClose() is a function that allows to run any code for 30 seconds before the server fully shuts down. Here's how you can solve it:

game:BindToClose(function()
    for _, v in pairs(game.Players:GetPlayers()) do
        local userId = v.UserId
        local data = v.leaderstats.Cash.Value
        local success, errorMessage = pcall(function()
            myDataStore:SetAsync(userId,data)
        end)
        if success then
            print("Data saved and server closed")
        else
            warn("Error while saving data: "..errorMessage)
        end
    end
end)

Source: DataModel:BindToClose()

0
I get the "data saved and server closed" but the data doesn't save? CaptainStevones123 12 — 4y
Ad

Answer this question