DatastoreService Data dont save

I was doing a cash system, I used datastoreservice but it seems to no save and always be 0 for some reason.

Game 1:
Error1

Game 2:
Error2

local DataStoreService = game:GetService("DataStoreService")
local CashStore = DataStoreService:GetDataStore("CashStore")
local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(Player)
	local CashValue = Instance.new("IntValue")
	CashValue.Name = "Cash"
	CashValue.Parent = Player
	
	local Success, Error = pcall(function()
		local PlayerCash = CashStore:GetAsync(Player.UserId)
		print(PlayerCash)
		if PlayerCash then
			CashValue.Value = PlayerCash
		end
	end)
	
	if Error then
		Player:Kick("Your Data did not load, Please try again")
	end
end)

game.Players.PlayerRemoving:Connect(function(Player)
	local Success, Error = pcall(function()
		CashStore:SetAsync(Player.UserId,Player.Cash.Value)
	end)
end)
3 Likes

Use BindToClose() for when the server shuts down.

game:BindToClose(function()
	for _, player in pairs(Players:GetPlayers()) do
		local Success, Error = pcall(function()
		      CashStore:SetAsync(Player.UserId,Player.Cash.Value)
	    end)
	end
end)
1 Like

First of all, do something like this at the end of the script:

game:BindToClose(function()
	for _, player in pairs(game.Players:GetPlayers()) do
		SaveData(player) --Replace the existing saving part of your script with a function
	end
end)

Edit: I also noticed that you aren’t defining the variable properly. It should look something like this:

	local PlayerCash --Add this to your script and remove the local two lines down
	local Success, Error = pcall(function()
		PlayerCash = CashStore:GetAsync(Player.UserId)
	end)
		if PlayerCash and Success then
			print(PlayerCash)
			CashValue.Value = PlayerCash
		elseif Error then
			warn(Error)
		end
	end)
2 Likes

I dont know how i really fixed it, but when i add 50 to the cash, it works, but when i change in the explorer , it dont work

You are probably changing it on the client inside of the server. Change your testing mode from client to server first and then change the value.

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