DataStore not saving value

I don’t know why but the value of the IntValue is not being saved.

Script:

local DSS = game:GetService("DataStoreService")
local NumberDS = DSS:GetDataStore("NumberDataStore")

game.Players.PlayerAdded:Connect(function(Player)
	local UserId = Player.UserId
	local data
	local success, errormessage = pcall(function()
		data = NumberDS:GetAsync(UserId.."_Number")
	end)
	if data ~= nil then
		workspace:WaitForChild("Values"):WaitForChild("Number").Value = data
	end
end)

game.Players.PlayerRemoving:Connect(function(Player)
	local UserId = Player.UserId
	local data = {workspace.Values.Number.Value}
	local success, errormessage = pcall(function()
		NumberDS:UpdateAsync(UserId.."_Number", function()
			return data
		end)
	end)
	if success then
		print("Data successfully saved!")
	else
		warn(errormessage)
	end
end)
1 Like

Use SetAsync() instead of UpdateAsync(). And at this line:

workspace:WaitForChild("Values"):WaitForChild("Number").Value = data

Change data to data[1] because you were setting the IntValue as a table when it’s supposed to be a number.

Also, add a BindToClose() function just in case the server shuts down.

game:BindToClose(function()
	
	for _, Player in pairs(game.Players:GetPlayers()) do
		local UserId = Player.UserId
		local data = {workspace.Values.Number.Value}
		local success, errormessage = pcall(function()
			NumberDS:SetAsync(UserId.."_Number", data)
		end)

		if success then
			print("Data successfully saved!")
		else
			warn(errormessage)
		end
	end
	
end)

So now, the whole thing should look like this:

local DSS = game:GetService("DataStoreService")
local NumberDS = DSS:GetDataStore("NumberDataStore")

game.Players.PlayerAdded:Connect(function(Player)
	local UserId = Player.UserId
	local data
	local success, errormessage = pcall(function()
		data = NumberDS:GetAsync(UserId.."_Number")
	end)
	
	if success then
		if data ~= nil then
			workspace:WaitForChild("Values"):WaitForChild("Number").Value = data[1]
		else
			print("There is no data.")
		end
	end
end)

game.Players.PlayerRemoving:Connect(function(Player)
	local UserId = Player.UserId
	local data = {workspace.Values.Number.Value}
	local success, errormessage = pcall(function()
		NumberDS:SetAsync(UserId.."_Number", data)
	end)
	
	if success then
		print("Data successfully saved!")
	else
		warn(errormessage)
	end
end)

game:BindToClose(function()
	
	for _, Player in pairs(game.Players:GetPlayers()) do
		local UserId = Player.UserId
		local data = {workspace.Values.Number.Value}
		local success, errormessage = pcall(function()
			NumberDS:SetAsync(UserId.."_Number", data)
		end)

		if success then
			print("Data successfully saved!")
		else
			warn(errormessage)
		end
	end
	
end)
2 Likes

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