Attempt to index nil with 'Humanoid"

I’m trying to make an attacking NPC weapon system and im getting ‘Attempt to index nil with Humanoid’
I know the reason that the humanoid is gone when the code are trying to find it resulting in breaking the script. Is there a way i can fix this?

Code:

if (unittorso.Position - torso.Position).magnitude < unitRange then
			unit:SetPrimaryPartCFrame(torso.CFrame)
			unithumanoid.WalkSpeed = 0
			track:Stop()
			track3:Play()
			task.wait(unitStats.Firerate)
			torso.Parent.Humanoid:TakeDamage(unitStats.Damage) -- this line
			track3:Stop()
			track2:Play()
		end

try usingmethod :waitforchild() on hunanoid

The issue here, according to that error, is that torso.Parent doesn’t exist (nil). You can fix this by using your already existing unithumanoid variable, however it’s strange that it’s already destroyed by the time you’re attempting to apply damage.

Also, I would recommend looking into memory leaks and garbage collection. You’ll want to set your instance variables to nil when you’re done with them, or else they’ll never be garbage collected from memory.

1 Like

Well unithumanoid and the torso are different. Torso is the enemies and unithumanoid is the unit itself

If it’s being destroyed when its health reaches 0, then you can just check to see if the Parent and the Humanoid exists before running the code, or just wrap everything in a pcall if you want to be lazy about it:

pcall(function() torso.Parent.Humanoid:TakeDamage(unitStats.Damage) end)

That will get rid of the error and allow the code to continue.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.