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

Why is this simple gun giving script not working and instead giving me an error?

I have a script and I want it to give the player a gun if they don't have one already. However when ever I run the script I get an error saying attempt to index local 'p' (a nil value). Here is my code.

while true do
	
local p = game.Players.LocalPlayer

if p.Backpack.AK-47 ~= nil then
	local tool = game.ServerStorage.AK_47:Clone()
	tool.Parent = p.Backpack
end

wait(1)	
	
end

I would really love some help

1 answer

✓ Accepted answer

If this is a Script, this won't work. Loop through all the players instead. I do not advise you do this with a LocalScript.

Fixed script:

while true do

for _,p in ipairs(game.Players:GetPlayers()) do
if not p.Backpack:FindFirstChild("AK_47") then
    local tool = game.ServerStorage.AK_47:Clone()
    tool.Parent = p.Backpack
end

wait(1) 

end
end


Another big error you have made is that the old script is actually giving the player the gun if they have it already. You also shouldn't use object == nil, you should do the following:

if not parent:FindFirstChild('objectname') then
--Code here
end

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