My game has been experiencing data loss and it’s from data getting rolled back, this is a big problem because what if they buy gems with robux and then lose it all, or someone gives them something for free and it disappears. This is my loading data code:
--load player data
local function loadData(player)
print(player)
local success = nil
local playerData = nil
local attempt = 1
repeat
success, playerData = pcall(function()
return dataBase:GetAsync(player.UserId)
end)
attempt += 1
if not success then
warn(playerData)
task.wait(1)
end
until success or attempt == 3
if success then
if not playerData then--give default data if they're new
playerData = {
["Gems"] = 0,
["SelectedTowers"] = {"Cameraguy"},
["OwnedTowers"] = {"Cameraguy"},
["MaxTowers"] = 5,
["RedeemedCodes"] = {},
["Wins"] = 0,
["Snowflakes"] = 0,
}
beamEvent:FireClient(player)
end
data[player.UserId] = playerData
isLoaded[player] = true
else
warn("Unable to get "..player.UserId.."'s data")
player:Kick("There was a problem getting your data")
end
end
for i, randomPlr in pairs(Players:GetPlayers()) do
loadData(randomPlr)
end
Players.PlayerAdded:Connect(loadData)
Players.PlayerAdded:Connect(function(player)
task.wait(1)
player.leaderstats.Wins.Value = data[player.UserId].Wins
end)
Saving data code:
--save player data
local function saveData(player)
print(player)
if data[player.UserId] and player.UserId ~= 0 and isLoaded[player] == true then
local success = nil
local playerData = nil
local attempt = 1
repeat
success, playerData = pcall(function()
return dataBase:UpdateAsync(player.UserId, function()
return data[player.UserId]
end)
end)
attempt += 1
if not success then
warn(playerData)
task.wait(1)
end
until success or attempt == 3
if success then
print("Data saved successfully")
else
warn("Unable to save data for player", player.UserId)
end
else
warn("No session data for", player.UserId)
end
isLoaded[player] = nil
end
Players.PlayerRemoving:Connect(function(player)
saveData(player)
data[player.UserId] = nil
end)
game:BindToClose(function() --if game shuts down
if not RunService:IsStudio() then
print("Shutting down")
for _, player in ipairs(Players:GetPlayers()) do
task.spawn(function()
saveData(player)
end)
end
else
print("Shutting down inside studio")
end
while not next(isLoaded) do -- we keep waiting until all player datas are saved and closed by the spawned functions
task.wait(1)
end
end)
Any help is appreciated since I rlly want this solved asap, thanks and have a good day!