AI stops after reaching waypoints

The AI I created stops after each waypoint it reaches, somewhere in my code I did set the NetworkOwner of its PrimaryPart, but this didn’t change anything. I think the problem may lie within the FindNearestTarget function, but I’m not sure. Here’s my code currently:

function spcall(func)
	pcall(spawn, func)
end

function ai.list:FindNearestTarget()
	local model = self.model
	local settings = self.settings
	local followRange = settings.Technical.FollowRange
	
	local least = math.huge
	local instanceTarget = nil
	local possibleTargets = {}
	
	for i, v in pairs(workspace:GetChildren()) do
		if isCharacter(v) then
			local mag = (v.PrimaryPart.Position-model.PrimaryPart.Position).magnitude
			if mag <= followRange and v ~= model then
				table.insert(possibleTargets, {
				["magnitude"] = mag;
				["instance"] = v
			})
			end
		end
	end
	
	for i, target in pairs(possibleTargets) do
		if target.magnitude < least then
			least = target.magnitude
			instanceTarget = target.instance
		end
	end
	
	return instanceTarget
end

function ai.list:Track()
	local model = self.model
	local settings = self.settings
	local humanoid = model:WaitForChild("Humanoid")
	
	local target = self:FindNearestTarget()
	
	if not target or self.hasTarget or not self.hasStarted then
		return
	end
	
	self.hasTarget = true
	
	local start = model.PrimaryPart
	local destination = target.PrimaryPart
	
	local pathFindingService = game:GetService("PathfindingService")
	
	local function follow()
		
		local path = pathFindingService:CreatePath(settings.PathfindingSettings)
		
		local created, err = pcall(function()
			return path:ComputeAsync(start.Position, destination.Position)
		end)
		
		local function redraw(connection)
			spcall(function()
				self.hasTarget = false
				self:Track()
				if connection ~= nil then
					connection:Disconnect()
				end
			end)
		end
		
		if created then
			
			local lastPos = destination.Position
			local pathChanged = false
			local changed = nil
			
			changed = destination.Changed:Connect(function()
				local currPos = destination.Position
				if (currPos-lastPos).magnitude > 3 then
					pathChanged = true
				end
			end)
			
			local waypoints = path:GetWaypoints()
			
			for _, point in pairs(waypoints) do
				spcall(function()
					if pathChanged then
						redraw(changed)
					end
				end)
				humanoid:MoveTo(point.Position)
				humanoid.MoveToFinished:Wait()
			end
			
			spcall(function()
				redraw(changed)
			end)
			
		else
			
			humanoid:MoveTo(start.Position)
			warn(err)
			
		end
		
	end
	
	follow()
	
end
2 Likes