Just wondering, what would be the best method to save data with DataStoreService? I know how to use both SetAsync and UpdateAsync, but when should I use them? What would be better, a spawned loop that auto-saves data every few seconds or a PlayerRemoving event that saves it when the player leaves?
Here's my code for both cases:
Auto-save method:
local Datastore = game:GetService("DataStoreService"):GetDataStore("Example")
local Inc = Datastore:GetAsync("Test") or 0
spawn(function()
while wait(5) do
print("Autosaving...")
Datastore:UpdateAsync("Test",function()
return New
end)
print("Saved")
end
end)
PlayerRemoving method:
local Players = game:GetService("Players")
local Datastore = game:GetService("DataStoreService"):GetDataStore("Example")
local Data = {}
Players.PlayerAdded:connect(function(Player)
Data[Player.UserId] = Datastore:GetAsync("Test") or 0
while wait(1) do
Data[Player.UserId] = Data[Player.UserId] + 1
end
end)
Player.PlayerRemoving:connect(function(Player)
Datastore:UpdateAsync(Player.UserId,function()
return Data[Player.UserId]
end)
end)
Confusion
I feel like the PlayerRemoving one is a lot better, and more efficient, but there are also times when it won't save. Whereas the auto-save method seems to work fine, but over a period of time takes longer to save data and doesn't seem to efficient. Any help?
