Help with npc ai

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

3 Likes

Humanoid:MoveTo() does not yield until it is finished. Try adding a Humanoid.MoveToFinished:Wait() after it.

2 Likes

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