Help on zombie script

I am currently making a game that has zombies in it, but the script that I use for the zombie has some bugs.
The main issue is that the zombie locks on tho a player and will not stop going for them until they are dead, and once that player is dead the zombie no longer goes after them.
is there a way to make it so the zombie calculates the closest player and goes after them, but still goes after them after they have died multiple times?

Any help would be greatly appreciated, this is my first post so if this is in the wrong section please say it.

Here is a download of my test place:
Baseplate.rbxl (52.7 KB)

local Zombie = script.Parent
local zombieHuman = Zombie:WaitForChild("Zombie")
local root = Zombie:WaitForChild("UpperTorso")

local hitbox = Zombie:WaitForChild("HitBox")

local DMG = 10

hitbox.Touched:Connect(function(hit)
	local human = hit.Parent:FindFirstChild("Humanoid")
	if human and hit.Parent.Name ~= "Zombie" then
		human.Health -= 5
	end
end)


function nearPersonPos()
	local closest
	local bestDist = 1000 
	for _,v in pairs(game.Players:GetPlayers()) do
		local char = v.Character
		local tors = char and char:FindFirstChild("UpperTorso")
		if not tors then continue end
		local dist = (tors.Position-root.Position).Magnitude
		if dist >= bestDist then continue end
		closest = tors.Position
		bestDist = dist
	end
	return closest
end

while zombieHuman.Health > 0 do
	zombieHuman:MoveTo(nearPersonPos() or root.Position) 
	wait(1)
end

:+1:
Have an Amazing and Awsome day.

Try doing this:

local character = player.Character or player.CharacterAdded:Wait()
1 Like

Where?
Sorry Iā€™m not that good at scripting.

1 Like
for _,v in pairs(game.Players:GetPlayers()) do
		local char = v.Character or v.CharacterAdded:Wait()
1 Like

It Worked!!!
Thank you!

This helped a lot!

1 Like