What Is Wrong With This DataStore Script?

So I made this data store script and I’m not sure whats wrong with it, it prints the success messages but the data still doesn’t load, I have API services on as wellas https. Any suggestions or solutions?

local DataStoreService = game:GetService("DataStoreService")
local CashStore = DataStoreService:GetDataStore("Cash")
local queue = 0
																				
game.Players.PlayerAdded:Connect(function(Player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = Player
	
	local Cash = Instance.new("IntValue")
	Cash.Name = "Cash"
	Cash.Value = 0
	Cash.Parent = leaderstats
	
	local data
	local Success, Error = pcall(function()
		data = CashStore:GetAsync(Player.UserId.."-cash")
	end)
	
	if Success then
		Cash.Value = data
		print("Data Found!")
	else
		warn(Error)
	end
end)

game.Players.PlayerRemoving:Connect(function(Player)
	queue += 1
	local Sucess, Error = pcall(function()
		CashStore:SetAsync(Player.UserId.."-Cash", Player.leaderstats.Cash.Value)
	end)
	
	if Sucess then
		print("Data Saved!")
		queue -= 1
	else
		warn(Error)
	end
end)

game:BindToClose(function()
	repeat wait() until queue == 0
end)


The data variable will be nil if there’s nothing saved to that key in the datastore. You can’t test saving on PlayerRemoving in studio because the server closes too fast, so you’ll need to go ingame to have it actually save.

Also you’re not doing anything in BindToClose yet. Might wanna save data for players still ingame there.

1 Like

on line 17 you typed “cash” and on line 31 you typed “Cash” - that’s the error
so to solve this change line 31 to:

CashStore:SetAsync(Player.UserId.."-cash", Player.leaderstats.Cash.Value)

yeah had to be more careful :sweat_smile: