Money System not working

So I made a vender/shop and when you click a button it checks if you have 10 or more bucks, and if you do it takes ten and print something, but that is not happening. This script is a normal script and the Money is an int value in a folder in the player.


local Button = game.StarterGui.Vender.MainFrame.Passport

Button.MouseButton1Click:Connect(function(Player)
	print("OnServer")
	local Money = Player.leaderstats.Money
	if Money >= 10 then
		Money = Money - 10 
		print("Bought")
	end
end)
3 Likes

you can’t use MouseButton1Click on a normal script, it has to be in a local script

1 Like

You will need a client script to detect the mouse click, and a server script to deduct money. To communicate the request between the two scripts, I recommend using a RemoteFunction. In addition, you are trying to set Player.leaderstats.Money to a number directly, but that object represents a NumberValue Instance, so you should be setting Player.leaderstats.Money.Value instead. Here is an example that should work for your case:

Local Script (in StarterGui):

local Button = script.Parent.Vender.MainFrame.Passport
local Player = game.Players.LocalPlayer
local BuyItem : RemoteFunction = game.ReplicatedStorage:WaitForChild("BuyItem")
Button.MouseButton1Click:Connect(function()
	local Success = BuyItem:InvokeServer()
end)

Server Script:

local BuyItem : RemoteFunction = game.ReplicatedStorage:FindFirstChild("BuyItem")

if BuyItem == nil then
	BuyItem = Instance.new("RemoteFunction")
	BuyItem.Name = "BuyItem"
	BuyItem.Parent = game.ReplicatedStorage
end

function BuyItem.OnServerInvoke(Player : Player)
	print("OnServer")
	local Money : NumberValue = Player.leaderstats.Money
	if Money.Value >= 10 then
		Money.Value = Money.Value - 10 
		print("Bought")
		return true
	end
	return false
end

You may want to expand on this by having multiple products the user can buy. You can accomplish this by having different Instances in workspace/ReplicatedStorage corresponding to different items the player can buy with their own prices, and passing this as an argument through the RemoteFunction. Good luck!

4 Likes

This worked, thank you! And if I were to add more items to buy, I would just add more instances and function for different events?

2 Likes

Ideally, you only need one function to purchase any item. You would create items as objects (or, more advanced, store them in a module script that the client and server share), and then add an argument to the function call to specify to the server which item you want to sell. For example: BuyItem:InvokeServer(Item) on the client and function BuyItem.OnServerInvoke(Player, Item) on the server.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.