Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

BEST way to save data?

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?

1 answer

✓ Accepted answer

Auto saving is almost always better in any situation, because unexpected situations can occur. But, every 5 seconds is a bit much.

In a game I made, I used both: I autosaved every 60 seconds, and also when the player left. Make sure that you use OnClose to make sure that the data actually saves before the last player leaves the game.

This discussion is preserved as it was. New answers, comments, and votes are closed.