Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

how resolve this error player(a nil value)?

  							 Output Players.Player1.PlayerGui.ShopGui.BackGround.items.item4.Script:5: attempt to index local 'Player' (a nil Value)
function Buy(Player)
	local RS = game:GetService("ReplicatedStorage")
	local item = RS:WaitForChild("Ball")
	local Price = 50
	local stats = Player.stats
	if (stats.Cash.Value >= Price) then
		item:Clone().Parent = Player.Backpack
		item:Clone().Parent = Player.StarterGear
		stats.Cash.Value = stats.Cash.Value - Price
	end
end

script.Parent.MouseButton1Click:connect(Buy)

2 answers

I'm guessing you were using leaderstats for this then I don't think it's gonna find something called "stats" inside Player if you used leaderstats then change it to Player.leaderstats

2 comments

0

I did not use his name as stats.

0

ye i know i wrote it before u updated it. before u didnt show the error so i could not tell what was the error.

The MouseButton1Click event does not return the player as an argument, this is why you're getting the error. You can use the LocalPlayer property of the Players service to get the current player.

local Player = game.Players.LocalPlayer --Only works in local scripts.

Your final code should look something like this:

local Player = game.Players.LocalPlayer --Gets the current player.
local stats = Player:WaitForChild("stats") --In case the stats object is not available, we can wait for it to be available by using WaitForChild.

function Buy()
    local RS = game:GetService("ReplicatedStorage")
    local item = RS:WaitForChild("Ball")
    local Price = 50
    if (stats.Cash.Value >= Price) then
        item:Clone().Parent = Player.Backpack
        item:Clone().Parent = Player.StarterGear
        stats.Cash.Value = stats.Cash.Value - Price
    end
end

script.Parent.MouseButton1Click:connect(Buy)

This discussion is preserved as it was. New answers, comments, and votes are closed.