Savescript not saving consistently

I am trying to make a script to save the amount of gold a player has. Although I have run into the problem that it does not consistently save the gold when someone leaves but it does when it auto saves every minute. I’ve made scripts before like this but this one is not working for some reason and I can’t find out why.

This is the save script
local dataStoreService = game:GetService("DataStoreService")
local storeData = dataStoreService:GetDataStore("storeData")
local Players = game:GetService("Players")

--Saved Data Table
--1: Gold the player has

game.Players.PlayerAdded:Connect(function(player)
	local playerUserID = player.UserId
	local setSuccess, errorMessage = pcall(function()
		return storeData:GetAsync(playerUserID)
	end)
	if setSuccess then
		local playerData = storeData:GetAsync(playerUserID)
		player:WaitForChild("PlayerStats").Gold.Value = playerData[1]
	end
	if not setSuccess then
		warn(errorMessage)
	end
end)

game.Players.PlayerRemoving:Connect(function(player)
	local playerUserID = player.UserId
	local SaveData = {}
	SaveData[1] = player.PlayerStats.Gold.Value
	local setSuccess, errormessage = pcall(function()
		print("saving")
		storeData:SetAsync(playerUserID, SaveData)
		print("save successful")
	end)
	if not setSuccess then
		warn(errormessage)
	end
end)

while true do
	wait(60)
	for i, player in pairs(Players:GetPlayers()) do
		local playerUserID = player.UserId
		local SaveData = {}
		SaveData[1] = player.PlayerStats.Gold.Value
		local setSuccess, errormessage = pcall(function()
			storeData:SetAsync(playerUserID, SaveData)
		end)
		if not setSuccess then
			warn(errormessage)
		end
	end
end

You need to add a Game:BindToClose function to save the players data, because the server shuts down before the last player leaves.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.