Leaderstats not saving

Hello fellow devforum users! I made a leaderstats script and would like it to save data, and it does. . . slightly. You see, it only saves the data if the data is added onto, but when I attempt to subtract from the data, it doesn’t save that.

Example: I earned 10 coins, it saves the coins value as 10 when I leave and rejoin. I spend 5 of the ten coins, it still saves as 10 when I leave and rejoin.

game.Players.PlayerAdded:Connect(function(plr)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = ("leaderstats")
	leaderstats.Parent = plr

	local cash = Instance.new("IntValue")
	cash.Name = "Coins"
	cash.Parent = leaderstats
	cash.Value = 0
	cash.Value = CashData:GetAsync(plr.UserId) or Value
	CashData:SetAsync(plr.UserId, cash.Value)

	game.Players.PlayerRemoving:Connect(function(plr)
		CashData:SetAsync(plr.UserId, plr.leaderstats.Coins.Value)
	end)
end)

all help is appreciated!

2 Likes

Have you tried moving the Player Removing Event out of the PlayerAdded Event? Also are you seeing any errors in the console?

1 Like

are you changing cash.value or just the leader stats number?

1 Like
local CashData = game:GetService('DataStoreService'):GetDataStore('CashData')

game.Players.PlayerAdded:Connect(function(plr)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = ("leaderstats")
	leaderstats.Parent = plr

	local cash = Instance.new("IntValue")
	cash.Name = "Coins"
	cash.Parent = leaderstats
	cash.Value = 0

	local succ, saved_data = pcall(function()
		return CashData:GetAsync(tostring(plr.UserId))
	end)

	if succ and saved_data ~= nil then
		cash.Value = saved_data
	end
end)

game.Players.PlayerRemoving:Connect(function(plr)
	local leaderstats = plr:FindFirstChild('leaderstats')
	local Cash = leaderstats:FindFirstChild('Coins')
	
	CashData:UpdateAsync(tostring(plr.UserId), function(old_data)
		return Cash.Value
	end)
end)

This will happen if you are changing the value from the client, changes made on client are not replicated to server.

Other than put your saves inside a pcall, to help prevent data loss

1 Like

Oh, the subtraction system might be in a local script :skull:

Edit: made the change, it works now!

1 Like

So far I have not seen an error in the console.

The script changes the cash value.

Thanks for the help I will try the script out!

Head to the View tab and click on Console.

Oh I made a typo. I edited the post, makes more sense now lol.

1 Like

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