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

how do I fix attempt to index nil with 'Backpack' error?

Asked by 4 years ago

So, I'm writing code to remove items from a plays inventory but im getting a error from line one. The error is "Attempt to index nil with 'Backpack' " and I'm not sure why. From what I know, this code is fine but it clearly isn't. Thank you!

local gear = game.Players.LocalPlayer.Backpack:GetChildren()

local function onTouch(hit)
    for i, child in ipairs(gear) do
        child:Destroy()
        print(game.Players.LocalPlayer.Name.." Inventory Cleared")
    end
end

game.Workspace.Door.Touched:Connect(onTouch)
0
Is the script a LocalScript? Azarth 3141 — 4y
1
No. Lol. Big brain time pokemine1o9 44 — 4y
0
Well, you can't use LocalPlayer in a ServerScript as it runs on the Server and not on the Client. killerbrenden 1537 — 4y
0
Now ive run into a nother error. When I touch the door, the inventory is not cleared. Any idea? pokemine1o9 44 — 4y

2 answers

Log in to vote
0
Answered by 4 years ago

If you're using a script on the door, you cannot have access the backpack in the LocalPlayer.

Ad
Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

Sorry that I'm a bit late. Anyways, LocalPlayer can only be used in a LocalScript. The way you can still reference a player here is by using :GetPlayerFromCharacter.

local function onTouch(hit)
    if hit.Parent:FindFirstChild("Humanoid") then -- checking if this is a player first because hit could be anything
        local player = game.Players:GetPlayerFromCharacter(hit.Parent) -- if the parent of the hit is a player's character, then the game will get the player OF that character
        for i, child in ipairs(player.Backpack) do
                child:Destroy()
                print(player.Name.." Inventory Cleared")
        end
    else
        print("Not a player")
    end
end

game.Workspace.Door.Touched:Connect(onTouch)

By the way, you don't have to use ipairs for your loop. The children of the backpack normally do not have keys, so you can just use the normal pairs for your loop instead.

Answer this question