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

[SOLVED] Attempt to index nil with 'Backpack'?

I've tried to make a scanner script that scans for contraband when the player touches a part and if found any it would change the light colour. I've managed to do some scripting but I still get an error saying "Attempt to index nil with 'Backpack'. The script changes the colour of the light to read once and then it gives this error. Also, the script won't change the light's colour to green even if the player has no contraband.

local contraband = {
	"AK74M",
	"USP"
}

local players = game:GetService("Players")

script.Parent.Touched:Connect(function(hit)
	local player = players:GetPlayerFromCharacter(hit.Parent)
	for i,v in pairs(player.Backpack:GetChildren()) do
		if table.find(contraband,v.Name) then
			script.Parent.Parent.Light.BrickColor = BrickColor.new("Maroon")
		elseif not table.find(contraband,v.Name) then
			script.Parent.Parent.Light.BrickColor = BrickColor.new("Bright green")
		end
	end
end)

3 comments

1

Try doing it where you define player as just hit.Parent. I think the GetPlayerFromCharacter function may be throwing the error because it's returning nil.

0

That would just give me the player's character but not the player. I need to get to the player's actual backpack.

0

I've also made a script before that looks nearly the same with the difference that there is no table and it removes all the player's tools when the player touches a part and that script works

2 answers

Try this and check if it works.

local contraband = {
    "AK74M",
    "USP"
}

local players = game:GetService("Players")

script.Parent.Touched:Connect(function(hit)

    for i,v in pairs(player.Backpack:GetChildren()) do
        if table.find(contraband,v.Name) then
            script.Parent.Parent.Light.BrickColor = BrickColor.new("Maroon")
        elseif not table.find(contraband,v.Name) then
            script.Parent.Parent.Light.BrickColor = BrickColor.new("Bright green")
        end
    end
end)

1 comment

0

Not working.

The problem was somehow in the part itself. When I walked through it, it returned this error but when I walked on it, it worked completely fine.

1 comment

0

If you got the answer then please accept it.

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