Problem with loading and saving Button Data

Hello, i’m trying to make a system where you can buy certain buttons for some cash and produce you passive income, the buttons should save and load back in the game every time you leave and rejoin, but for some reason i dont understand why the code isn’t working. Can someone help me please.


local DataStoreService = game:GetService("DataStoreService")
local playerDataStore = DataStoreService:GetDataStore("PlayerData")

game.Players.PlayerAdded:Connect(function(player)
	local key = "Player_" .. player.UserId
	local success, data = pcall(function()
		return playerDataStore:GetAsync(key)
	end)

	-- Setup leaderstats
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	local currency = Instance.new("IntValue")
	currency.Name = "Currency"
	currency.Value = 0
	currency.Parent = leaderstats

	local prestigePoints = Instance.new("IntValue")
	prestigePoints.Name = "PrestigePoints"
	prestigePoints.Value = 0
	prestigePoints.Parent = leaderstats

	-- Setup PlayerData
	local playerData = Instance.new("Folder")
	playerData.Name = "PlayerData"
	playerData.Parent = player

	local ownedButtons = Instance.new("Folder")
	ownedButtons.Name = "OwnedButtons"
	ownedButtons.Parent = playerData

	if success and data then
		-- Restore data
		currency.Value = data.Currency or 0
		prestigePoints.Value = data.PrestigePoints or 0

		for buttonID, isOwned in pairs(data.OwnedButtons or {}) do
			local attribute = Instance.new("BoolValue")
			attribute.Name = buttonID
			attribute.Value = isOwned
			attribute.Parent = ownedButtons
		end
	else
		warn("Failed to load data for player:", player.Name, data)
	end
end)

game.Players.PlayerRemoving:Connect(function(player)
	local key = "Player_" .. player.UserId
	local leaderstats = player:FindFirstChild("leaderstats")
	local playerData = player:FindFirstChild("PlayerData")
	local ownedButtons = playerData and playerData:FindFirstChild("OwnedButtons")

	if leaderstats and ownedButtons then
		local buttonData = {}
		for _, attribute in pairs(ownedButtons:GetChildren()) do
			buttonData = attribute.Name
		end

		local success, err = pcall(function()
			playerDataStore:SetAsync(key, {
				Currency = leaderstats.Currency.Value,
				PrestigePoints = leaderstats.PrestigePoints.Value,
				OwnedButtons = buttonData
			})
		end)

		if not success then
			warn("Failed to save data for player:", player.Name, err)
		end
		print("Saving Data:", {
			Currency = leaderstats.Currency.Value,
			PrestigePoints = leaderstats.PrestigePoints.Value,
			OwnedButtons = buttonData
		})
	end
end)


2 Likes

Hello!

I’m a little confused on what you mean, what exactly isn’t working, the loading or saving function?
Also are you sure there aren’t any errors in console?