So, I’m making a game and i want to make a global leaderboard that will show the total money earned by the player, but I’m saving the total money value in a table with the other values (money, items…) as you can see in this part of the code:
game.Players.PlayerRemoving:Connect(function(player)
local playerUserId = player.UserId
local library = {
moneyAmount = player.leaderstats.Money.Value,
totalMoney = player.moneyEarned.Value
}
local setSuccess, errorMessage = pcall(function()
moneyStore:SetAsync(playerUserId, library)
end)
if setSuccess then
print("Save success")
else
print("Save failed, error: "..errorMessage)
end
end)
I have watched some tutorials and docs to figure out how to do it but I still can’t get it, would I need to save it in a different way?
You are saving it correctly, you just need to test it in the actual game. Studio closes the game before PlayerRemoving runs. To fix it for studio, use game:BindToClose(function()
game:BindToClose(function()
for _, player in pairs(game.Players:GetPlayers()) do
local playerUserId = player.UserId
local library = {
moneyAmount = player.leaderstats.Money.Value,
totalMoney = player.moneyEarned.Value
}
local setSuccess, errorMessage = pcall(function()
moneyStore:SetAsync(playerUserId, library)
end)
if setSuccess then
print("Save success")
else
print("Save failed, error: "..errorMessage)
end
end
end)
As has been suggested, if you want the DataStore to save while in studio you’ll need to make use of the instance method “:BindToClose()” which binds a function to the closing of the server (when the server is closed the binded function, if any, is executed), this is necessary because in studio the “PlayerRemoving” event doesn’t always fire (as the server is locally hosted it is often closed faster then the player instance is removed), if you tested this same script in a live session of the experience (where servers are hosted by Roblox) then you’ll notice that the DataStore saving is operational. As a final note, be wary that the timeout of a function binded to the closing/shutting down of a server is 30 seconds (so make sure the bound function can execute itself fully within that 30 second time frame).