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)
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.