Attempt to index nil with 'Destroy'

Hello, I am fairly average at scripting and I’m not sure why this is happening.

When the model touches the lava it will be destroyed, however this works but it’s constantly spamming errors as seen in the clip below.

Here is the code used:

local function onTouch(hit) 
	
	local humanoid = hit.Parent:FindFirstChild("Humanoid") 
	
	if not humanoid then
		task.wait(1)
		hit.Parent:Destroy()
	else
		humanoid.Health = 0 
	end
end

script.Parent.Touched:connect(onTouch)

Does anybody know why this is happening? Thanks.

1 Like

The error says you’re attempting to index nil with the Destroy() method. As a result, the parent of hit is nil. In other words, you’re trying to destroy something that doesn’t exist.

Check if the parent exists before calling Destroy():

local function onTouch(hit) 	
local humanoid = hit.Parent:FindFirstChild("Humanoid") 	
  if not humanoid then
    task.wait(1)
    if hit and hit.Parent then
      hit.Parent:Destroy()
    end
  else
    humanoid.Health = 0 
  end
end

script.Parent.Touched:connect(onTouch)
2 Likes

I understand now, thank you very much for your help! :slight_smile:

1 Like

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