Attempt to index nil with Humanoid

So I was modifying a script to fit my game. In my game your most likely going to die alot on purpose meaning that this error would be quite annoying.
This is the code:

function onTouched(hit)
	if hit.Parent:findFirstChild("Humanoid") and hit.Parent.Humanoid ~= nil then
	hit.Parent.Humanoid:TakeDamage(100)
	end
end

script.Parent.Touched:connect(onTouched)

The error being:

 [19:11:28.086 - Workspace.Beam.Damage:2: attempt to index nil with 'findFirstChild']

Can someone point out how to fix this problem?

1 Like
function onTouched(hit)
    if hit.Parent:findFirstChild("Humanoid") then
    hit.Parent.Humanoid:TakeDamage(100)
    end
end

script.Parent.Touched:connect(onTouched)

I just removed the " hit.Parent.Humanoid ~= nil" part, since you detected the humanoid with ā€œhit.Parent:findFirstChild("Humanoid")ā€. Sorry, Iā€™m bad at explaining.

By the way, findFirstChild and connect are deprecated. I would recommend using FindFirstChild and Connect.

2 Likes