Value not updating when player leaves

  1. What do you want to achieve? Save a table of data

  2. What is the issue? My code does not update the variable “cash.” When I edit the value in-game it still saves as the original value.

  3. What solutions have you tried so far? I’ve tried changing the path and updating the value in a loop.

local DSS = game:GetService("DataStoreService")
local currencyDS = DSS:GetDataStore("currencyDS")

game.Players.PlayerAdded:Connect(function(plr)
	
	-- stuff to save 

	local currency = Instance.new("Folder")
	currency.Name = "Currency"
	currency.Parent = plr
	
	local cash = Instance.new("NumberValue")
	cash.Name = "Cash"
	cash.Parent = currency
	
	local currencyMult = Instance.new("NumberValue")
	currencyMult.Name = "CurrencyMult"
	currencyMult.Parent = currency
	currencyMult.Value = 1
	print(currencyMult.Value)
	
    -- sets data into a table to save multiple values, makes a player UID a key for datastores

	local playerUID = "player_" .. plr.UserId
	
	local data = {}
	
	-- fetches datastore data and saves it

	local success, err = pcall(function()
		data = currencyDS:GetAsync(playerUID)
		
	end)
	if success then
		print("Success")
		if data then
			print("data collected")
			

			cash.Value = data[1]
			print(data[1], data[2])
			currencyMult.Value = data[2]
			
			
		else

			--without a datastore it will make the player not have any cash

			cash.Value = 0
			currencyMult.Value = 1
		end
	else
		warn(err)
	end
end)

game.Players.PlayerRemoving:Connect(function(plr)
	local cash = plr.Currency.Cash.Value
	print(cash)
	local currencyMult = plr.Currency.CurrencyMult.Value

	local data = {cash, currencyMult}
	
	
	local playerUID = "player_" .. plr.UserId
	
	-- saves data when leaving

	local success, err = pcall(function()
		currencyDS:SetAsync(playerUID, data)
	end)

	if success then
		print("data saved")
		print(cash)
	else
		warn(err)
	end


end)
1 Like

Make sure in game settings API services are enabled. If not, you won’t be able to use data saves. They’re automatically disabled for safety reasons.

Also, I see you’re storing two pieces of data in the table you’re saving. the cash, and a another variable I assume is a currency multiplier. I don’t know if you already tried this but I wouldn’t do that. I would use two datastores. Or, you could investigate a little more into this:

Also, you should consider reviewing the part of your script where you check if data then. You may be setting it to 0 every time you join the game, because you haven’t set up the statement properly.

One tip too, (I’m not so experienced in data saves) you should make sure you can save tables to data stores.

1 Like