Data Storage not saving data issue

I want to make the values saves but its not working.

When I’m entering the game and earning some “Cash” and then leaving its not saving or not reading data when I’m entering again.

How can I fix that?

Script:

local DataStoreService = game:GetService("DataStoreService")
local dataStore = DataStoreService:GetDataStore("NeckDataStore")

game:GetService("Players").PlayerAdded:Connect(function(Player)
	local PlayerStatus = Instance.new("Folder")
	PlayerStatus.Name = "PlayerStatus"
	PlayerStatus.Parent = Player
	local NeckCount = Instance.new("IntValue")
	NeckCount.Value = 1
	NeckCount.Name = "NeckCount"
	NeckCount.Parent = PlayerStatus
	local Cash = Instance.new("IntValue")
	Cash.Value = 35
	Cash.Name = "Cash"
	Cash.Parent = PlayerStatus
	local CurrentBackpack = Instance.new("StringValue")
	CurrentBackpack.Value = ""
	CurrentBackpack.Name = "CurrentBackpack"
	CurrentBackpack.Parent = PlayerStatus
	local CurrentBackpackCapity = Instance.new("IntValue")
	CurrentBackpackCapity.Value = 0
	CurrentBackpackCapity.Name = "CurrentBackpackCapity"
	CurrentBackpackCapity.Parent = CurrentBackpack
	
	local Backpacks = Instance.new("Folder")
	Backpacks.Name = "Backpacks"
	Backpacks.Parent = Player
	local Backpack0 = Instance.new("BoolValue")
	Backpack0.Value = true
	Backpack0.Name = "Backpack0"
	Backpack0.Parent = Backpacks
	local Backpack1 = Instance.new("BoolValue")
	Backpack1.Value = false
	Backpack1.Name = "Backpack1"
	Backpack1.Parent = Backpacks

	local data
	local success, err = pcall(function()
		data = dataStore:GetAsync(Player.UserId)
	end)
	if success then
		
		Player.PlayerStatus.Cash.Value = data[1]
		
	else
		print("The player has no data!")
	end
end)

local function saveData(player)
		local tableToSave = {
			player.PlayerStatus.Cash.Value
		}

		local success, err = pcall(function()
			dataStore:SetAsync(player.UserId, tableToSave)
		end)

		if success then
			print("Data has been saved!")
		else
			print("Data hasn't been saved!")
			warn(err)		
		end
end

game.Players.PlayerRemoving:Connect(function(player)
	saveData(player)
end)

game:BindToClose(function()
	for _, player in pairs(game.Players:GetPlayers()) do
		saveData(player)
	end
end)

The problem

My suggestion/Solution

Move SaveData above PlayerAdded.Within PlayerAdded we add an autosave at the very bottom

while Player do
wait(30) -- forgot a wait my bad lol (._. SHOULD NOT BE LESS THAN 30
saveData(Player)
end

or

Use what was suggested in the post I linked above as the problem

1 Like

Its still not working. When I putted print(data[1]) it prints “35” not last cash value :sad:

Did you wait for it to save maybe add a print to know if it has saved. What suggested did you use

I just saw that my value is changing only in client-side not server-side.

1 Like