Attempt to index nil with 'leaderstats'

I’m trying to subtract money from player but this error appear:

Already tried to change WaitForChild() position and switched the script to localscript.

Code:

function buy(player)

	local cash = player.leaderstats:WaitForChild("Money")
	local price = script.Parent.Parent.Price

	if cash.Value >= price.Value then
		cash.Value = cash.Value - price.Value
		print("bought")
	end

end

script.Parent.MouseButton1Click:Connect(buy)

The reason this isn’t working is because player is nil, not the leaderstats. This is why the error says you are trying to index nil (the player) with leaderstats (which has already loaded).

Here are a couple things you should do to effectively solve your problem:

  1. Because you are trying to detect when a gui button is being clicked, this should be in a local script
  2. MouseButton1Click doesn’t take a player parameter. Use game.Players.LocalPlayer instead.
  3. Fire a remote event to the server when changing leaderstats. This will prevent exploiters from affecting their stats.
4 Likes