Attempt to index nil with 'Destroy'

I am working on a zombie defense game, and I came across an error in a script called “attempt to index nil with ‘Destroy’”

script:

local Health = script.Parent.Health

while wait(0) do
	if Health.Value <= 1 then
		script.Parent:Destroy()
	end
end

Thanks for helping if you can, it will be well appreciated!

Where is the script in? Is this inside a humanoid?

It’s happening because it’s destroying it many times, so when the condition is met, even if it’s destroyed, it’ll still try to destroy it, and thus will try to destroy nil. I would recommend setting up a Died event on the humanoid so when the zombie is dead, destroy them

local hum = script.Parent

hum.Died:Connect(function()
	hum.Parent:Destroy()
end)

If there’s an event that can prevent an unneeded infinite while loop, use it. It should be what is needed for you since you were originally destroying the humanoid only, instead of the entire player

3 Likes

Thanks a lot! It works just as I wanted thanks for the help!

1 Like

Anytime! If you have anymore issues don’t be afraid to make another post!