DataStore not working

Hello!

I made a script where it saves players data. The script somehow isn’t working, no errors, it only prints out that it saved the data, but didnt print out when it got the data. I’m so confused on how it’s not working, I saw some posts, but they were really confusing, and most of them had no solution.

local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetDataStore("DataStore1")

game.Players.PlayerAdded:Connect(function(player)
	local leaderstats = Instance.new("Folder", player)
	leaderstats.Name = "leaderstats"

	local Cash = Instance.new("IntValue", leaderstats)
	Cash.Name = "Cash"
	
	local Data 
	
	local success, errormes = pcall(function()
		local Data = DataStore:GetAsync(player.UserId.."-Cash")
	end)
	
	if success then
		Cash.Value = Data
	else
		warn("somethings wrong with getting or setting the data")
		warn(errormes)
	end
end)

game.Players.PlayerRemoving:Connect(function(player)
	local success, errormes = pcall(function()
		DataStore:SetAsync(player.UserId.."-Cash", player.leaderstats.Cash.Value)
	end)
	
	if success then
		print("data saved")
	else
		print("data failed to save")
		warn(errormes)
	end
	
end)

You’re defining Data as a local variable in the pcall function, instead of assigning it to the variable, Data.

1 Like

It works, thank you so much! :grinning:

1 Like