Data not saving/loading?

I’m making a datastore to save a player’s amount of money that they have, but for some reason the data is not saving/loading. I do not know what is going on, because the script is not producing any errors.

local DataStoreService = game:GetService("DataStoreService")
local playerData = DataStoreService:GetDataStore("playerData")

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local gold = Instance.new("IntValue")
	gold.Name = "Gold"
	gold.Parent = leaderstats
	
	local data
	local firstJoinData
	local sucess, err = pcall(function()
		data = playerData:GetAsync(player.UserId.."-gold")
	end)
	
	if sucess then
		gold.Value = data
	else
		print("Not able to retrieve data")
		warn(err)
	end
end)

game.Players.PlayerRemoving:Connect(function(player)
	local sucess, err = pcall(function()
		playerData:SetAsync(player.UserId.."-gold", player.leaderstats.Gold.Value)
	end)
	if sucess then
		print("Data was saved")
	else
		warn(err)
	end
end)

game.ReplicatedStorage.SaveEvent.OnServerEvent:Connect(function(player)
	local sucess, err = pcall(function()
		playerData:SetAsync(player.UserId.."-gold", player.leaderstats.Gold.Value)
	end)
	if sucess then
		print("Data was saved")
	else
		warn(err)
	end
end)


game:BindToClose(function()
	for _, player in ipairs(game.Players:GetPlayers()) do
		local sucess, err = pcall(function()
			playerData:SetAsync(player.UserId.."-gold", player.leaderstats.Gold.Value)
		end)
		if sucess then
			print("Data was saved")
		else
			warn(err)
		end
	end
end)

I made it save when the player leaves the server, when the server shuts down, and for when a cutscene that is also in the game has finished. It works fine in studio, but when I run the game on Roblox the data is not pulled back. I have tested this on other people, and if I manually change their data from Roblox it saves fine.
Any ideas on what is going on?

Probably you did set gold’s value on a LocalScript, remember DataStores are server-sided, so you will need to use a RemoteEvent.

1 Like