.I am making a shop gui for a game and I made a simple button that detects whether or not the player has enough money when they try to purchase an item, and if they do it gives them they item and subtracts the money from their account. The script is very basic but it gives me an error code saying "Attempting to index local "player" (a nil value).
script.Parent.MouseButton1Click:connect(function(player) local lstats = player:WaitForChild('leaderstats') if lstats.Tokens.Value >= 60 then lstats.Tokens.Value = lstats.Tokens.Value - 60 else script.Parent.Text = 'Insufficient Funds!' end end)
I'm tried doing it in both local and global scripts and added a wait feature but neither worked, how would I get this to work in a local script?
The reason that your script broke is that player is not a parameter to the RobloxScriptSignal [event] MouseButton1Click
. If this is in a local script, which it should be, because all scripts that work in the PlayerGui, or StarterGui must be LocalScripts due to FilteringEnabled then you would try this method:
local player = game.Players.LocalPlayer script.Parent.MouseButton1Click:connect(function() local lstats = player:WaitForChild('leaderstats') if lstats.Tokens.Value >= 60 then lstats.Tokens.Value = lstats.Tokens.Value - 60 else script.Parent.Text = 'Insufficient Funds!' end end)
But that probably won't work online because of FIltering Enabled. Your best bet is to use this method of using RemoteFunctions
Step 1: put a RemoteFunction in the ReplicatedStorage named HandleTransaction
Step 2: Put these in your game
Replace your script with this LocalScript and put it in the same place.
local player = game.Players.LocalPlayer local rf = game.ReplicatedStorage:WaitForChild("HandleTransaction") script.Parent.MouseButton1Click:Connect(function() local transaction = rf:InvokeServer() if not transaction then script.Parent.Text = 'Insufficient Funds!' end end)
Insert a Script inside the ServerScriptStorage
local rf = game.ReplicatedStorage:WaitForChild("HandleTransaction") function re.OnServerInvoke(player) if player:FindFirstChild("leaderstats") and player.leaderstats:FindFirstChild("Tokens") then if player.leaderstats.Tokens.Value >= 60 then player.leaderstats.Tokens.Value = player.leaderstats.Tokens.Value - 60 -- if you want something to happen as a result of the transaction, like giving the player an item, put the code here. return true else return false end end end