need help to make npc go to cloesest plr tried for a hour, couldnt get it working
repeat
for i, p in pairs(game.Players:GetPlayers()) do
local hrp = script.Parent.HumanoidRootPart
local char = p.Character
local closestCharacter
if char and char:FindFirstChild("HumanoidRootPart") and char.Humanoid.Health > 0 then
local distance = (char.HumanoidRootPart.Position - hrp.Position).Magnitude
if not closestCharacter then closestCharacter = char end
local closestDistance = (closestCharacter.HumanoidRootPart.Position - hrp.Position).Magnitude
if distance < closestDistance then
closestCharacter = char
end
end
if closestCharacter then
script.Parent.Humanoid:MoveTo(closestCharacter.HumanoidRootPart.Position)
end
end
task.wait(0.2)
until script.Parent.Humanoid.Health <= 0