How do i fix this error which shows characterModel attempt to index nil with 'destroy'

I’m working on script for a character that kills other characters. Once the player dies i got this error when the players been removed from the workspace…

image

local zombieTorso = script.Parent.Torso
local zombieHumanoid = script.Parent.Humanoid

local function findTarget()
	local agroDistance = 100
	local target = nil
	for i, v in pairs(game.Workspace:GetChildren()) do
		local human = v:FindFirstChild("Humanoid")
		local torso = v:FindFirstChild("Torso")
		if human and torso and v~= script.Parent then
			-- Check distance
			if (zombieTorso.Position - torso.Position).magnitude < agroDistance then
				agroDistance = (zombieTorso.Position - torso.Position).magnitude
				target = torso
				
			end
		end
	end
	return target
end

while wait(2) do
	local torso = findTarget()
	if torso then
		zombieHumanoid:MoveTo(torso.Position)
		
			for i, v in pairs(game.Workspace:GetChildren()) do
			zombieHumanoid.Touched:Connect(function(v)
				local human = v.Parent:FindFirstChild("Humanoid")
			if human then
					human:TakeDamage(human.MaxHealth)
					wait(3)
					local characterModel = human.Parent
		            characterModel:Destroy()
			end				
		end)
	end
	else
		zombieHumanoid:MoveTo(zombieTorso.Position + Vector3.new(math.random(-50,50), 0, math.random(-50,50), 0))
	end
end

Your code is saying that after 3 seconds (after damaging the player), destroy the character model. From the looks of this, you didn’t include a debounce, so whenever the player touches the zombie in any way, it triggers this behavior. That’s why it kills the player instantaneously. As for the :Destroy() error you have pointed out, it’s because the default respawn time for a character is 3 seconds. Your character model doesn’t exist, and therefore can’t be destroyed.

A simple guard clause can fix this

local characterModel = human.Parent
if not characterModel then return end
characterModel:Destroy()

That being said, I’m not sure if destroying the player character is intentional, but this will fix that error.