Datastore won't work for some reason

I’m trying to write a dynamic settings system, and I wrote this code. It seems to load, but saving isn’t working. Why is this and why isn’t it working?

local players = game.Players
local DataStoreService = game:GetService("DataStoreService")
local replicatedStorage = game.ReplicatedStorage
local datastore = DataStoreService:GetDataStore("PlayerOptions")

local template = game.ServerStorage.OptionsTemplate

players.PlayerAdded:Connect(function(player)
	local playerOptions = template:Clone()
	playerOptions.Parent = game.ReplicatedStorage.PlayerOptions
	playerOptions.Name = player.Name
	
	local success, errorMsg = pcall(function()
		local data = datastore:GetAsync(tostring(player.UserId))
		print("Data: ",data)
		if data then
			for option,value in pairs(data) do
				local valueObj = playerOptions:FindFirstChild(option,true)
				valueObj.Value = value
				print("Key: ",option,", Value: ",value)
			end
		end
	end)
	
	if not success then warn(errorMsg) end
end)

players.PlayerRemoving:Connect(function(player)
	local playerOptions = replicatedStorage.PlayerOptions:FindFirstChild(player.Name)
	local saveData = {}
	
	local success, errorMsg = pcall(function()
		for idx, obj in pairs(playerOptions:GetDescendants()) do
			if obj:IsA("ValueBase") then
				saveData[obj.Name] = obj.Value
			end
		end
		
		print(saveData)
		
		datastore:SetAsync(tostring(player.UserId),saveData)
	end)

	if not success then warn(errorMsg) end
	
	playerOptions:Destroy()
end)

Add this to the end of the script to give the game time to save:

game:BindToClose(function()
    task.wait(3)
end)

If that doesn’t work, try to test your datastore outside of studio. Some people have issues with data saving in studio.

1 Like

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