AI causing lag spikes

I found that the AI for enemies in a test place i made were causing short lag spikes everytime ComputeASync was called

local function Main(Position, Part:BasePart)
	warn("Executted")
	if Position then
		local Mag = (Root.Position - Position).Magnitude
		--local Sight = CheckSight(Part)
		if Mag > Range.Value or Part then
			
			local Success = pcall(function() Path:ComputeAsync(Root.Position, Position) end)  -- the current assumption is that waypoints are causing high memory usage
			local CurrentIndex = 0
			warn("Creating path")
			if Success and Path and Path.Status == Enum.PathStatus.Success then
				warn("Success")
				Pathing = true
				Blocked = false
				if BlockConn then
					BlockConn:Disconnect()
					BlockConn = nil
				end
				BlockConn = Path.Blocked:Connect(function(BlockedIndex) -- Make this a one time connection from what i figured
					if BlockedIndex >= CurrentIndex then
						warn("Lol blocked")
						Blocked = true
					end 
				end)
				local Points:{PathWaypoint} = Path:GetWaypoints()
				if DebugMode then
					DebugPath(Points)
				end
				task.spawn(function()
					for i, v in Points do
						if not Active.Value or Humanoid:GetState() == Enum.HumanoidStateType.Dead or not Pathing then
							break
						end
						Waypoint = v
						CurrentIndex = i
						task.wait((16/Humanoid.WalkSpeed)/4)
					end
				end)
			else
				warn("Path creation unsuccessful", Path.Status)
				--Blocked = true
			end
		end
	end
end

If i remove the pcall for ComputeASync, lag would occur than this error would follow.


note that this occured on a very large but empty baseplate
I’ve seen AI freak out like this when an enemy used a laser beam attack that used parts for VFX for i do not know why.
And to prove it was the AI, This is what i got in microprofiler

image
and this is what the navmesh looks like

![image|690x363](upload://ptB3kraLHuRh5BUh

And AI computes every 4 seconds or if the path is blocked or if it sees the target to which it shorten the cooldown to .2 seconds but won’t compute anymore paths

2 Likes