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