Data Store not working when player leaves game

I am trying to save the coins a player has when they leave the game but it isn’t working.

game.Players.PlayerRemoving:Connect(function(player)
	local char = player.Character
	local success, errormessage = pcall(function()
		print("Left Game")
		CoinsData:UpdateAsync(player.UserId.."-Coins", player.leaderstats.Coins.Value)
	end)
end)

After the player leaves the game it is still printing “Left Game” but the coin value isn’t saving.

I am not a datastore expert, but I’m pretty sure it’s SetAsync() and not UpdatesAsync(). Also, you need to give their datastore values when they join the game.

1 Like

It may also error due to as the player is leaving and may never find the associated character

:UpdateSync() takes in two parameters, a key and a callback function. The callback function takes in the current value of what is saved inside the key and returns a new value that is essentially going to be saved within that key.

In this case, you’re doing it all wrong. You haven’t set up the callback function nor return anything. This code below should work.

You also should do the same thing with game:BindToClose()

game.Players.PlayerRemoving:Connect(function(player)
	local success, result = pcall(function()
		CoinsData:UpdateAsync(player.UserId, function(oldValue)
			return player.leaderstats.Coins.Value
		end)
	end)
	
	if success then
		print("Player's data has been saved!")
	else
		print("Oops, an error occured!: " .. result)
	end
end)