Hey.
I’m trying to save a level datastore when the player leaves:
game.Players.PlayerRemoving:Connect(function(player)
dsLevel:UpdateAsync(player.UserId, function(oldValue)
local newValue = oldValue or 0
newValue = player.leaderstats.Level.Value
return newValue
end)
end)
but for some reason, it always saves 0 as the dsLevel.
When I try writing newValue = newValue + 50, it works fine and increases the value saved by 50 every time.
I do not have any idea what function(oldValue) is in line 2 of your script, but I believe that is your problem. Could you provide more detail on it please, so we can help?
Here is an article on datastores to help you understand UpdateAsync and GetAsync:
have you checked the server if it changes the value? The client can’t do all of that. Sometimes when we look at the value, we see that it changes in the client, but not always in the server.
Level’s Value, you need to make sure it changes in the server, so it can be saved into the games data. The link I provided at the top should help you understand why data stores are server-sided only.
The script you provided should work, i think there is else at play here. First ensure that this is on the server( handled on the server) and for testing purposes place a print(newValue) right before the return in the Update Async function , to see what it prints
I had to use game:BindToClose because for some reason my cash didn’t save if I was the last player left on the server. If you decide to try that be aware that in studio game:BindToClose will cause 30 seconds of (Not Responding) → BindToClose 100% Infinite Yield
(EDIT): If you don’t want to use BindToClose then I would suggest implementing autosave system that saves the value to datastore when player.leaderstats.Level.Value changes. Use player.leaderstats.Level:GetPropertyChangedSignal("Value"):Connect