I need help saving and loading data store

  1. I tried some solution in the dev hub and yt.

I’m creating a gui level system in which the level increases and cash when it reaches the required xp.

Here is my leaderstats and data store.

local DataStoreSer = game:GetService("DataStoreService")
local PlayerData = DataStoreSer:GetDataStore("DataTestxdsds")

game.Players.PlayerAdded:Connect(function(Player)
	local leaderstats = Instance.new("Folder", Player)
	leaderstats.Name = "leaderboard"
	local Cash = Instance.new("NumberValue", leaderstats)
	Cash.Name = "Cash"
	
	local Level = Instance.new("NumberValue", leaderstats)
	Level.Name = "Level"
	
	local XP = Instance.new("NumberValue", leaderstats)
 	XP.Name = "XP"
	local ReqXP = Instance.new("NumberValue", Player)
	ReqXP.Name = "ReqXP"
	ReqXP.Value = Level.Value*5
	
	XP.Changed:Connect(function(Changed)
		if XP.Value >= ReqXP.Value then
			XP.Value = 0
			
			Level.Value += 1
			ReqXP.Value = Level.Value*5
			Cash.Value += 100
		end
	end)
	
	-- Data
	local playerUserID = 'Player'..Player.UserId
	local data = PlayerData:GetAsync(playerUserID)
	if data then
		print("Data found. [DATA LOADED]")
		Cash.Value = data["Cash"]
		Level.Value = data["Level"]
		XP.Value = data["XP"]
	else
		print("No data found. [NEW PLAYER]")
		Cash.Value = 0
		Level.Value = 0
		XP.Value = 0
	end
end)

local function create_table(Player)
	local player_stats = {}
	for _, stat in pairs(Player.leaderboard:GetChildren()) do
		player_stats[stat.Name] = stat.Value
	end
	return player_stats
end

game.Players.PlayerRemoving:Connect(function(Player)
	local player_stats = create_table(Player)
	local success, err = pcall(function()
		local playerUserID = 'Player'..Player.UserId
		PlayerData:SetAsync(playerUserID, player_stats)
	end)
	
	if success then
		print("Your data successfully saved!")
	else
		warn("Could not save your data.")
	end
end)

u can use this

-- Saving Stats
game.Players.PlayerRemoving:connect(function(player)
	local datastore = game:GetService("DataStoreService"):GetDataStore(player.Name.."Stats")

local savestats = player:FindFirstChild("leaderstats"):GetChildren()
for i =  1, #savestats do
	datastore:SetAsync(savestats[i].Name, savestats[i].Value)
	print("saved data number "..i)
	
end
print("Stats successfully saved")	
end)
-- Loading Stats
game.Players.PlayerAdded:connect(function(player)
		local datastore = game:GetService("DataStoreService"):GetDataStore(player.Name.."Stats")
	
	player:WaitForChild("leaderstats")
	wait(1)
	local stats = player:FindFirstChild("leaderstats"):GetChildren()
	for i = 1, #stats do			
	stats[i].Value = datastore:GetAsync(stats[i].Name)
	print("stat number "..i.." has been found")
		end
end)

place it on new server script

1 Like

Thank you, it works, and I discovered my mistake with the xp giver. I just need to increase the time from 5 seconds to 10+ seconds to allow the data store to load.