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!
I believe the source of your issues may be the spawn
as it will cause the function to run in a separate thread that will be culled as the game shuts down. Make sure anything you do in BindToClose stays within the same environment so it can continue running as the game shuts down. I would suggest adding more print statements throughout the code to get a more in-depth play-by-play of how the code is running.
Locked by JesseSong
This question has been locked to preserve its current state and prevent spam and unwanted comments and answers.
Why was this question closed?