Data not saving when player leaves

I want to save the game level and exp progress when the player leaves, but it’s failing for some reason.

On the client I have this:

Player.PlayerRemoving:Connect(function(player)
	print("Saving! " .. expInt.Value .. " " .. level)
	Save:FireServer(expInt.Value, level)
	print("fired save event")
end)

which then outputs this in the output.

Saving! 1155 903
fired save event

And on the server I have this:

local DataStoreService = game:GetService("DataStoreService")
local experienceStore = DataStoreService:GetDataStore("PlayerExperience")
local levelStore = DataStoreService:GetDataStore("PlayerLevel")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Save = ReplicatedStorage:WaitForChild("Save")

Save.OnServerEvent:Connect(function (player, exp, level)
	print("Saving Stage 2")
	local playerUserID = player.UserId
	print(playerUserID .. " " .. exp .. " ".. level)
	local success, newExperience = pcall(function(playerUserID)
		return experienceStore:SetAsync(playerUserID, exp)
	end)

	if success then
		print("New Experience:", newExperience)
	end
	local success, newLevel = pcall(function(playerUserID)
		return levelStore:SetAsync(playerUserID, level)
	end)

	if success then
		print("New Level:", newLevel)
	else
		print("failed :(")
	end
end)

And the output:

Saving Stage 2
115898141 1155 903
failed :(

This keeps failing and I don’t know why.
I’ve tried increasing the time between each save and there are no errors in the output.

Remove playerUserID from the pcall’s parameters, and it should work.

1 Like

While what @C_Sharper said will fix your problem, I do not recommend using a remoteevent to save player’s data. That will allow hackers to easily change their data.

1 Like

Ah. Damn no wonder it looked weird to me compared to my script for loading data. Thanks!

Then how should I do it? ;-; Sorry i’m pretty new

whenever they leave.

game.Players.PlayerRemoving:Connect(function(Player)

end)

just use a playerRemoving event on the server and save from there. it would look something like this

game.Players.PlayerRemoving:Connect(function(plr)
	--get their current data and save it.
end)
1 Like

Oh! Thank you all so much! Alr i guess this was solved pretty fast