Need Urgent help with datastore!

Hey! I’m trying to save the cash in my game, so that when you leave your cash saves.
to me, It looks like ive done everything right. Please ask questions if you need.

The script:

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

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.Parent = leaderstats
	
	local playerUserId = "Player_"..player.UserId
	
	--load data
	
	local data
	local success,errormessage = pcall(function()
		 data = myDataStore:GetAsync(playerUserId)
	end)
	
	cash.Value = data
	
	if success then
		cash.Value = data
		--set data equal to plsyers current cash
		
	end
	
	myDataStore:GetAsync(playerUserId)
	
end)

game.Players.PlayerRemoving:Connect(function(player)
	local playerUserId = "Player_"..player.UserId
	
	local data = player.leaderstats.cash.Value
	
	local success, errormessage = pcall(function()
		myDataStore:SetAysnc(playerUserId,data)
	end)
	
	if success then
		print("Data Successfully saved.")
	else
		print("There was an error when saving the data.")
		warn(errormessage)
	end
	
end)
local Data = game:GetService("DataStoreService"):GetDataStore("TheDS1")
local Players = game:GetService("Players")
local Connections = {}
local SpeedOfUpdate = 0; -- Time in seconds between value updates.

local function PlayerAdded(Player)
	local Success, Stats, Error = pcall(function() return Data:GetAsync(tostring(Player.UserId)) end)
	if not Success and Error then
		warn(Error)
	else
		local StatFolder = Instance.new("Folder")
		StatFolder.Name = "leaderstats"
		local Stat1 = Instance.new("NumberValue")
		Stat1.Name = "Cash"
		
		Stat1.Value = Stats and Stats[1] or 0
		
		Stat1.Parent = StatFolder
		StatFolder.Parent = Player
	end
end

Players.PlayerAdded:Connect(PlayerAdded)

Players.PlayerRemoving:Connect(function(Player)
	if Connections[Player] then Connections[Player]:Disconnect() end
	local Folder = Player:FindFirstChild("leaderstats")
	local Success, Error = pcall(function() 
		Data:SetAsync(tostring(Player.UserId),{
			Folder.Cash.Value,
		})
	end)
	if not Success then
		warn(Error)
	else
		Folder:Destroy()
	end
end)

game:BindToClose(function()
	wait(1)
end)
2 Likes

You named IntValue “Cash” while you’re trying to index it as “cash” later in the code. It’s supposed to be player.leaderstats.Cash.Value

2 Likes

Thank you soo much1 It worked!! do you have a twitter? ill follow you if you do. or if you have any other social media! im so gratefull!