Help with metal detector script

I am trying to make a metal detector but it keeps erroring when something without a humanoid touches the doorway.

local way = script.Parent.DoorWay
local screen = script.Parent.Screen
local players = game:GetService("Players")
local badTools = {"Gun", "Hammer", "Knife"}

way.Touched:Connect(function(blockTouched)
	if blockTouched.Parent then
		if blockTouched.Parent.Humanoid then
			local hum = blockTouched.Parent.Humanoid
			local plr = blockTouched.Parent
			local inventory = players:GetPlayerFromCharacter(plr).Backpack
			local backpackItems = inventory:GetChildren()
			for itemName, itemValue in pairs(backpackItems) do 
				if itemName == badTools then 
					print("Weapon")
				end
			end
		end
	end
end)
1 Like

This is like an airport metal detector.

By doing blockTouched.Parent.Humanoid, you are assuming the Humanoid is inside of the enclosing object (blockTouched.Parent). Since you don’t know if it exists, you need to do this method instead:

blockTouched.Parent:FindFirstChild("Humanoid")

You should always use the :FindFirstChild method when trying to access a game object, since you don’t know if it exists for sure or not.

So here is your code with it fixed:

way.Touched:Connect(function(blockTouched)
	if blockTouched.Parent and blockTouched.Parent:FindFirstChild("Humanoid") then
		local hum = blockTouched.Parent.Humanoid
		local plr = blockTouched.Parent
		local inventory = players:GetPlayerFromCharacter(plr).Backpack
		local backpackItems = inventory:GetChildren()
		for itemName, itemValue in pairs(backpackItems) do 
			if itemName == badTools then 
				print("Weapon")
			end
		end
	end
end)

You may not even need the check for blockTouched.Parent, but I’ve kept it anyway.

EDIT: @mineblue5 method is even better for checking for a humanoid (FindFirstChildOfClass rather than FindFirstChild) since Humanoid can have a different name at times.

3 Likes

If the error is “Humanoid is not a valid member of Class Object Name” use blockTouched.Parent:FindFirstChildOfClass(“Humanoid”)

1 Like

Also, You should use table.find(badTools, itemValue.Name), Instead of itemName == badTools.