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

How do you fix "attempt to index local 'player'"?

local player = workspace:FindFirstChild("Player")

if player.TeamColor==BrickColor.new("Medium stone grey") then
	print("Player is a civilian, no shot ammo for you!")
	
	elseif player.TeamColor==BrickColor.new("Bright red") or player.TeamColor==BrickColor.new("Navy blue") or player.TeamColor==BrickColor.new("Navy blue") then
	script.Parent.ClickDetector.MouseClick:connect(function(plr)
 	ypcall(function()
 	for _,v in pairs(plr.Character:children()) do if v:IsA("BasePart") then v.Anchored = false end end
 	script.Parent.AmmoGiver:Clone().Parent = plr.PlayerGui
end)
end)
end

11:05:24.855 - Workspace.Limber.Ammo Box.Innards.Clicky.Script:3: attempt to index local 'player' (a nil value)

How do I fix this?

2 answers

local players = game.Players:GetPlayers()
for _, player in pairs(players) do
if player.TeamColor==BrickColor.new("Medium stone grey") then
    print("Player is a civilian, no shot ammo for you!")

    elseif player.TeamColor==BrickColor.new("Bright red") or player.TeamColor==BrickColor.new("Navy blue") or player.TeamColor==BrickColor.new("Navy blue") then
    script.Parent.ClickDetector.MouseClick:connect(function(plr)
    ypcall(function()
    for _,v in pairs(plr.Character:children()) do if v:IsA("BasePart") then v.Anchored = false end end
    script.Parent.AmmoGiver:Clone().Parent = plr.PlayerGui
end)
end)
end
end

WaitForChild() will wait until the Instance exists while FindFirstChild() searches for this Instance. And if this Instance is nil when the script starts running then the variable will be too.

The new problem now is that yours only gets a single character named "Player". If this Instance is nil then the team will of course not work.

4 comments

0

Thank you, although while there is now no error, it doesn't work either

0

I'll edit my answer and try to fix it with that.

0

Still doesn't work, darn.

0

Oh, well, I only fixed the part with getting the players. I could totally rewrite it for you if you want.

15 days later (I'm lazy) and I got it to work myself!!

script.Parent.ClickDetector.MouseClick:connect(function(plr)


if plr.TeamColor==BrickColor.new("Medium stone grey") then return
else
ypcall(function()
for _,v in pairs(plr.Character:children()) do if v:IsA("BasePart") then v.Anchored = false end end
script.Parent.AmmoGiver:Clone().Parent = plr.PlayerGui
end)
end
end)

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