I've been trying fix this problem of not saving my variables, I'm using 2 variables and I'm also using leaderstats with 2 intValues. I do not know why my data isn't saving. This is server script, and it's in ServerScriptService. The print statement at line 44 works, however, the print statement at line 64 doesn't.
local DSS = game:GetService("DataStoreService")
local mDS = DSS:GetDataStore("MyDataStore")
game.Players.PlayerAdded:Connect(function(player)
local key = player.UserId
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local wins = Instance.new("IntValue")
wins.Name = "Wins"
wins.Parent = leaderstats
local xp = Instance.new("IntValue")
xp.Name = "XP"
xp.Parent = leaderstats
local data
local success, ErrorCode = pcall(function()
return mDS:GetAsync(tostring(key))
end)
if success then
if data then
wins.Value = data["Wins"]
xp.Value = data["XP"]
end
else
warn("Error while saving: "..ErrorCode)
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local key = player.UserId
local dataTable = {
Wins = player.leaderstats.Wins.Value,
XP = player.leaderstats.XP.Value
}
local success, ErrorCode = pcall(function()
mDS:SetAsync(tostring(key),dataTable)
end)
if success then
print("Data saved!")
else
warn("Error while saving: "..ErrorCode)
end
end)
game:BindToClose(function(player)
local key
for _, v in pairs(game:GetService('Players'):GetPlayers()) do
key = v.UserId
local dataTable = {
Wins = v.leaderstats.Wins.Value,
XP = v.leaderstats.XP.Value
}
spawn(function()
local success, ErrorCode = pcall(function()
mDS:SetAsync(tostring(key),dataTable)
end)
if success then
print("Data2 Saved!")
else
print("Error While Saving:"..ErrorCode)
end
end)
end
end)
I've tested this both in-game and in studio and they do not work. Also, if possible, how can I change mDS:SetAsync to mDS:UpdateAsync? Any help is appreciated. Edit: I switched to DataStore2 (as recommended by some people and friends) and so far, it actually saved my data. To future people who read this, just because I used DataStore2, doesn't mean you should either. Use either DataStoreService or DataStore2, depending which one is easier. Best of luck, future developers!

3 comments
I suspect that I might know the problem. Try moving the code out of the spawn(). If that works, then I will post an answer explaining it.
That spawn is supposed to be just in case the code doesn't finish before the server shut down. Also it still doesn't work. Thanks for helping!
The code will definitely execute before the game shuts down because it's in :BindToClose.