Saving Data Without Using BindToClose

I’m trying to test out some things in my game and my datastore is sometimes not saving. I’m pretty sure I know this is because the server is closing before my data is saved, but I don’t want to use a BindToClose function because that fires along with the player removing and it gives a warning in the output. You can see I put a wait() after the saving in the script in hopes that the server would get some time to save the data before closing, but it still occasionally doesn’t save. Should I increase the wait time? Try another method? Or is using BindToClose seriously the only good way to ensure data saves when the server closes?

game.Players.PlayerRemoving:Connect(function(plr)
	local id = plr.UserId
	local statsfolder = plr.PlayerStats
	local coinvalue = statsfolder.CoinsValue.Value
	local totalxpvalue = statsfolder.TotalXP.Value
	local levelvalue = statsfolder.Level.Value
	local alltimetiles = statsfolder.AllTimeTilesDestroyed.Value
	local ranknumber = statsfolder.RankNumber.Value
	local statmultiplier = statsfolder.StatMultiplier.Value
	
	local statsTable = {coinvalue, totalxpvalue, levelvalue, alltimetiles, ranknumber, statmultiplier}
	statsStore:SetAsync(id, statsTable)
	wait()
end)
local PlayersSaving = 0


game.Players.PlayerRemoving:Connect(function(plr)
	PlayersSaving += 1
	local id = plr.UserId
	local statsfolder = plr.PlayerStats
	local coinvalue = statsfolder.CoinsValue.Value
	local totalxpvalue = statsfolder.TotalXP.Value
	local levelvalue = statsfolder.Level.Value
	local alltimetiles = statsfolder.AllTimeTilesDestroyed.Value
	local ranknumber = statsfolder.RankNumber.Value
	local statmultiplier = statsfolder.StatMultiplier.Value

	local statsTable = {coinvalue, totalxpvalue, levelvalue, alltimetiles, ranknumber, statmultiplier}
	statsStore:SetAsync(id, statsTable)
	PlayersSaving -= 1
end)


game:BindToClose(function()
	wait(1)
	repeat
		wait(.5)
	until
		PlayersSaving <= 0
end)

BindToClose only fires when the game closes, not when a player leaves.

1 Like