Hey so i’m using a data store right now. Loading the values works perfectly but it does not always save when I leave. Sometimes it saves sometimes it doesn’t. Usually it saves but sometimes it doesn’t. When it doesn’t save there is no warnings printed and it just doesn’t say “Successfully saved data”. Why would this code be inconsistent? How can I make it more consistent?
local function SaveData(player)
if data[player.UserId] then --- data is a table which stores all the usersIDs in it with all their stats among it.
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 did not save retrying")
task.wait()
end
until success or attempt == 6
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")
end
end
game:BindToClose(function()
if not RunService:IsStudio() then
for index, player in pairs(Players:GetPlayers()) do
task.spawn(function()
SaveData()
end)
end
end
end)
game:BindToClose(function()
if not RunService:IsStudio() then
for index, player in pairs(Players:GetPlayers()) do
task.spawn(function()
SaveData()
end)
end
end
task.wait(3)
end)
Thats the problem right there, the function SaveData() is getting called twice. First, when PlayerRemoving gets fired, it saves the actual data and sets the data[player.UserId] to nil. And then SaveData() gets called again in BindToClose. But the second time, it saves nil since you set the data[player.UserId] to nil the first time.
Put this code instead
game:BindToClose(function()
if RunService:IsStudio() then
task.wait(2)
end
end)