How do I save a player's data before he leaves?

Hello. I’m making a game, and I need to save a player’s activity data. His data updates every second, so sending a request to update the data store’s key every 1 second is a bad idea. Now, I’ve tried PlayerRemoving, but it fires after the player has already left, so I can’t really get the updated value. Now my question is, what event should I use for that?

If you have a value stored in his player object (game.Players), player.Removing will be enough to save.

Another thing I sometimes do is,
on the main script, have an array with all the player information, when someone leaves just grab that information and save it.
To update the information you can use a remoteEvent.

Side note, avoid overusing SetAsync and GetAsync, one every second is way way too much and it will take a lot of time to save each time. So avoid using them unless really needed

5 Likes

Huh?
Simply save his leaderstats with the player parameter, his leaderstats don’t get destroyed in that one second he leaves.

local players = game:GetService("Players")

players.PlayerRemoving:Connect(function(plr)
	local leaderstats = plr:WaitForChild("leaderstats")
	local cash = leaderstats:WaitForChild("Cash")
	repeat 
		local success, errormessage = pcall(function()
			DataStore:SetAsync(plr.UserId, cash.Value)
		end)
	until success 
end)
4 Likes

Just wanted to add something your script, you can use the pcalls in a much shorter way and it actually looks much cleaner like this:

local success, response = pcall(DataStore.SetAsync, DataStore, plr.UserId, cash.Value)
2 Likes

I’ve never heard of that. Thanks, I guess!

1 Like

Also, could you explain how that works, please?

pcall(DataStore.SetAsync, DataStore, plr.UserId, cash.Value)

I know that DataStore:SetAsync() is the same as DataStore.SetAsync(DataStore) but shouldn’t that be

pcall(DataStore.SetAsync(DataStore, plr.UserId, cash.Value))

?
Thanks.

So basically, you can’t use a : inside the pcall, so you define which Function you want to use as the first argument, the second argument is the object that the function belongs to basically the self.

The third and fourth, are basically the arguments you are passing to that function.

3 Likes

I know, but PlayerRemoving fires after the player has already left, so I can’t really get the value.
But still got an idea how to make it with PlayerRemoving.
Thank you! :slight_smile:

If you aren’t sure with how something works, the API Reference is good to learn from.

As explained in it, PlayerRemoving is run just before the player leaves and by then I believe its enough time to save your data and all.

2 Likes