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