Cash Saving Not Working

Hey!

My saving script for cash isn’t working. No errors are printing and success is being printed.

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

local CashDataStore = DataStoreService:GetDataStore("CashDataStore")

Players.PlayerAdded:Connect(function(player)
	
	local key = player.UserId
	
	local CashRig1 = Instance.new("NumberValue", player:WaitForChild("CharacterValuesRig1"))
	CashRig1.Name = "Cash"
	CashRig1.Value = 0
	
	local CashRig2 = Instance.new("NumberValue", player:WaitForChild("CharacterValuesRig2"))
	CashRig2.Name = "Cash"
	CashRig2.Value = 0
	
	------------------------
	local Data 
	
	local success, errorMessage = pcall(function()
		
		Data = CashDataStore:GetAsync(key)
		
	end)
	
	if success then
		
		print("Success Loading Cash Data")
		
		CashRig1.Value = Data["CashRig1"]
		CashRig2.Value = Data["CashRig2"]
		
		game:GetService("ReplicatedStorage").JobSystemEvents.CashLoaded:FireClient(player)
		
	else
		warn(errorMessage)
	end
	
end)

Players.PlayerRemoving:Connect(function(player)
	local key = player.UserId

	local Data = {
		
		["CashRig1"] = player:WaitForChild("CharacterValuesRig1").Cash.Value,
		["CashRig2"] = player:WaitForChild("CharacterValuesRig2").Cash.Value
		
	}
	
	local success, errorMessage = pcall(function()
		
		CashDataStore:SetAsync(key, Data)
		
	end)
	
	if success then
		print("Success Saving Cash Data")
	else
		warn(errorMessage)
	end
	
end)

Thanks

Alright, Did you test this in the game and studio?

I tested it in only studio. Should I test in game?

You should and let me know if it works.

1 Like

You should use BindToClose

BindToClose will fire once there are no players on the server and the server needs to shut down . It will stop the server from closing for up to 30 seconds so that it has time to run the function. Once the function runs or 30 seconds have passed, the server will close.

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