Problem on making a shop using leaderstats

Hello developers,
Recently I have been trying to make my own game and I wanted to make a leaderstat system where the player earns money each 5 seconds and it saves after leaving. then here is the issue , I wanted to make a shop GUI which removes the money from the leaderstats and gives the item to the player

First I made a Script on ServerScriptService for the leaderstats here I show it

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local MoneyDataStore = DataStoreService:GetDataStore("PlayerMoney")

local function savePlayerData(player)
	local success, error = pcall(function()
		MoneyDataStore:SetAsync(player.UserId .. "_Money", player.leaderstats.Money.Value)
	end)
	if not success then
		warn("Error saving data for player " .. player.Name .. ": " .. error)
	end
end

local function loadPlayerData(player)
	local success, data = pcall(function()
		return MoneyDataStore:GetAsync(player.UserId .. "_Money")
	end)
	if success and data then
		player.leaderstats.Money.Value = data
	end
end

local function giveMoney()
	for _, player in ipairs(Players:GetPlayers()) do
		if player and player.Parent then
			player.leaderstats.Money.Value = player.leaderstats.Money.Value + 10 -- Adjust the amount of money earned here
		end
	end
end

local function playerAdded(player)
	-- Create leaderstats if they don't exist
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player

	-- Create money stat
	local money = Instance.new("IntValue")
	money.Name = "Money"
	money.Value = 0 
	money.Parent = leaderstats

	-- Load player's money from DataStore
	loadPlayerData(player)
end

local function playerRemoving(player)
	savePlayerData(player)
end

-- Connect events
game.Players.PlayerAdded:Connect(playerAdded)
game.Players.PlayerRemoving:Connect(playerRemoving)

-- Give money every 5 seconds
while true do
	giveMoney()
	wait(5)
end

Then I already created the GUI for the shop. The parent of the buy button is a frame and I don’t know how to make a script to make the money be removed from the leaderstats after buying as well as giving the item without damaging the giving money system. How do i do it?

I already checked multiple resources and I don’t find any way to connect it to my existing leaderstats without interfering with the ServerScriptService script.

If someone can help me, I appreciate it.

you would have to have a way to detect the buy event, if not already done.

once the event is fired you’d have to subtract the desired amount from the money value. subtracting money from a value will in no way shape or form break the script above.

as for giving them an item you can just clone it into their backpack.

2 Likes