Help with enemy pathfinding Script

Hello everyone!
I have a problem with humanoid.MoveToFinished:Wait() , because my code is written in a way that every second the path to the player is updated, but the while task.wait(1) loop won’t start a new iteration because the humanoid hasn’t reached it’s destination. I’ve asked Grok 3, Claude 3.7, o3 mini and none of them can fix it.

Here’s the full script:

local torso = script.Parent:WaitForChild("Torso")

local humanoid = script.Parent:WaitForChild("AttackableHumanoid")

local PathfindingService = game:GetService("PathfindingService")

local players = game:GetService("Players")

function findNearestPlayer(pos)
	local minDistance = math.huge
	local nearestChar = nil

	for _, player in pairs(players:GetPlayers()) do
		local char = player.Character
		if char then
			local hrp = char:FindFirstChild("HumanoidRootPart")
			if hrp then
				local distance = (hrp.Position - pos).Magnitude
				if distance < minDistance then
					minDistance = distance
					nearestChar = char
				end
			end
		end
	end
	return nearestChar
end

local hostilePathfind = coroutine.create(function()	
	while task.wait(1) do
		if findNearestPlayer(torso.Position) then
			local path = PathfindingService:CreatePath()

			path:ComputeAsync(torso.Position, findNearestPlayer(torso.Position):WaitForChild("HumanoidRootPart").Position)

			for i, waypoint in pairs(path:GetWaypoints()) do
				humanoid:MoveTo(waypoint.Position)
				
				humanoid.MoveToFinished:Wait()
			end
		end
	end
end)

coroutine.resume(hostilePathfind)

I would recommend watching this tutorial to really understand more about your Enemy Pathfinding. This guy explains well on how to make a good Enemy AI.

2 Likes