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

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

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)

4 comments

0

Is the script a LocalScript?

1

No. Lol. Big brain time

0

Well, you can't use LocalPlayer in a ServerScript as it runs on the Server and not on the Client.

0

Now ive run into a nother error. When I touch the door, the inventory is not cleared. Any idea?

2 answers

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

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.

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