Datastore saving old data

So, my script is saving the data of the player, but it is saving the wrong data. It is saving the cash that the player has when they join the game, not when they leave. For example, if a player joined the game with 150 cash, and left with 1,150 cash, it saves 150 cash. Script below

Server:

local dataStores = game:GetService("DataStoreService")
local playerData = dataStores:GetDataStore("playerData")
local StarterGui = game:GetService("StarterGui")


game.ReplicatedStorage.save.OnServerEvent:Connect(function(player)
	local success, err = pcall(function()
		local cash = player.leaderstats.Cash.Value
		playerData:SetAsync("Player_" .. player.UserId, cash)
	end)
	if success then
		print("Saved " .. player.leaderstats.Cash.Value .. " for " .. player.Name)
	elseif err then
		error(err)
	end
end)

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder", player)
	leaderstats.Name = "leaderstats"
	local cash = Instance.new("IntValue")
	cash.Name = "Cash"
	cash.Parent = leaderstats
	cash.Value = playerData:GetAsync("Player_" .. player.UserId)
	workspace.playerCount.Value += 1
	--[[while true do
		wait(60)
		local success, err = pcall(function()
			local cash = player.leaderstats.Cash.Value
			playerData:SetAsync("Player_" .. player.UserId, cash)
		end)
		if success then
			print("Saved " .. player.leaderstats.Cash.Value)
		elseif err then
			error(err)
		end
	end--]]
end)

game.Players.PlayerRemoving:Connect(function(player)
	local success, err = pcall(function()
		local cash = player.leaderstats.Cash.Value
		playerData:SetAsync("Player_" .. player.UserId, cash)
	end)
	if success then
		print("Saved " .. player.leaderstats.Cash.Value)
	elseif err then
		error(err)
	end
	workspace.playerCount.Value -= 1
end)

game:BindToClose(function()
	if game["Run Service"].IsStudio then
		wait(3)
	end
end)

Local:

while true do
	wait(60)
	game.ReplicatedStorage.save:FireServer()
end
1 Like

Can you make sure that you are changing their money on the server?

1 Like

I’m not, gonna fix that right now

Thanks a lot for your help!!!