Saving data not working

I have tried to create a data storing system for currency in the game, but after following a tutorial, it doesn’t save the currency when I leave the game. The currency system otherwise works fine, and I want to note that I HAVE enabled studio access to API services in the game settings.

local DataStoreService = game:GetService("DataStoreService")

local dVersion = 1
local save = DataStoreService:GetDataStore("Currency "..dVersion)

game.Players.PlayerAdded:Connect(function(player)  
	local previousData = save:GetAsync(player.UserId)
	
	local currency
	
	if previousData ~= nil then
		currency = previousData
	else
		currency = 0
		save:SetAsync(player.UserId, 0)
	end
	
	local currencyValue = Instance.new("NumberValue", player)
	currencyValue.Name = "Currency"
	currencyValue.Value = currency
end)

game:BindToClose(function()
	for i,player in pairs(game.Players:GetPlayers()) do
		local value = player.Currency.Value

		if value ~= nil then
			save:SetAsync(player.UserId, value)
			print("Data Saved")
		end
	end
end)

game.Players.PlayerRemoving:Connect(function(player)  
	local value = player.Currency.Value
	
	if value ~= nil then
		save:SetAsync(player.UserId, value)
		print("Data Saved")
	end
end)

Thanks in advance.

2 Likes

Are you testing the game in Studio? Usually, Studio does not fire :PlayerRemoving, which means that your data will not be saved in Studio (regardless of enabling access to API Services). Try testing the script in the published version of the game.

It also looks like your script is saving the value only if the value is not equal to nil. This means that if data was previously saved in the DataStore used, it will not work (unless the value is nil)

Try removing the if statement surrounding the SetAsync function.

He doesn’t need to even check that it’s not nil since it comes directly from a number value, which can never be nil.

I believe it’s because the server is closing before it can work through all the data. Try putting game:BindToClose(function() wait(5) end)
at the very end of your script outside of the PlayerRemoving

It depends on the purpose of the DataStore.

What I’m saying is that it’s impossible for value to be nil in this situation.

Removing the if statements around the SetAsync function didn’t work

It won’t make a difference. The if statement was just unnecessary.

Test it in the actual game, instead of Studio. Usually Studio does not fire PlayerRemoving.