How to save data right before a player leaves?

I’m trying to change a players data as their leaving, ive tried looking at other threads but none of them have worked. This is my script:

game.Players.PlayerRemoving:connect(function(plr)
	local char = plr.Character or plr.CharacterAdded:Wait()
	local leaderstats = plr:WaitForChild("leaderstats")
	local cash = leaderstats:WaitForChild("Wiped")
	
	if char.CombatTag.InCombat.Value == true then
		warn("clogged")
				WipedData:SetAsync(plr.UserId, true)
		warn("clogged2")

		
	end
	
end)

The issue is that it prints “clogged” but it wont save the data or print “clogged2”

Its recommended to have a game:BindToClose to ensure your Data saves properly.

But a couple of things, I recommend you wrap SetAsync within a pcall so there arent any errors that occur with the code as SetAsync can fail at anytime.
Second, why do you have this if its not used?

How would I set that up when a player leaves?

Its not meant to be fired when the Player Leaves, Its meant to be fired when the Server Closes, Typically in Real Servers, when everyones leaves there will be about 30 seconds before the Server actually closes, which is where game:BindToClose will fire, its common use in DataStores is to ensure Data is saved, but another use is to yield the Server to wait for the Data of a Player to completely save, which is typically used in Studio.
game:BindToClose is also helpful for when the Servers shutdown unexpectedly, sometimes PlayerRemoving will not fire, but game:BindToClose to ensure that the data will save.

A way you can set this up is too store each Players data inside a table with the index as their UserId, that way its easily accessable, Like a type of Session Data system, and everytime the data is updated in game., update the Players Data in the table, so when the Player leaves, you can save the Data Stored in the table, as for game:BindToClose, iterate through the entire table, save the Data to each id, and then remove the index.

1 Like

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