Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by
TNTeon -1
6 years ago

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

Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

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
Ad

Answer this question