Pathfinding AI Lagging When Moving

I Need help with my Path finding Script.

It Keeps On Lagging, After About 20 Seconds It Starts To Lag.

I Have seen other Post about this Topic but The Solutions I Have Seen are Not For My Situation

Becuase of other people having Different Scripts.

I Have tried returning In the Move Function Using A Varaible, Just Like A Debounce To Stop The Function From Going On But it didnt work. I Have also re-wrote My Whole Script
To Make Sure I Didnt Miss Any Mistakes.

----------- Script --------------

ā€“ Varaibles

local ps = game:GetService(ā€œPathfindingServiceā€)
local human = script.Parent:WaitForChild(ā€˜Humanoidā€™)
local root = script.Parent:WaitForChild(ā€œHumanoidRootPartā€)
local runservice = game:GetService(ā€œRunServiceā€)
local debounce = false

local path = ps:CreatePath()

ā€“ Find Target Function

function findtarget()
local dist = 150
local target

for i, v in pairs(workspace:GetChildren()) do
	if v:FindFirstChild('Humanoid') and v.Name ~= script.Parent.Name then
		if (v.HumanoidRootPart.Position - script.Parent.HumanoidRootPart.Position).Magnitude < dist then
			dist = (v.HumanoidRootPart.Position - script.Parent.HumanoidRootPart.Position).Magnitude
			
			target = v.HumanoidRootPart
		end
	end
end
return target

end

ā€“ Move To Target Function

function moveto()
local target = findtarget()

if target then
	path:ComputeAsync(root.Position, target.Position)
	
	if path.Status == Enum.PathStatus.Success then
		local waypoints = path:GetWaypoints()
		
		for i, v in ipairs(waypoints) do
			
			human:MoveTo(v.Position)
			
			local finish = human.MoveToFinished:Wait()
			if not finish then
				break
			end
			
		end
	elseif path.Status == Enum.PathStatus.NoPath then return end
		
		
end

end

ā€“ While Loop

while wait(0.1) do

moveto()

end

2 Likes

Are you just recalculating over and over a path that cannot be traversed?

while wait(0.1) do
end

Is the part Iā€™m talk about. I donā€™t know our AI logic, but if the AI is constantly trying to pathfind to an invalid spot over and over, that could cause lag. You should also check if you have any memory leaks

2 Likes

How do I know if its in a Invalid spot?? Also how do I make it, if you know how, To not lag or continue a path over and over again?

1 Like

Quick question first. How are you testing this? Do you just stand by the AI or are you flying? Try moving humanoids around near and far the AI.

Iā€™m an intermediate scripter so I honestly donā€™t know either. This could be something else in the game? Have you tried to disable the AI and see if the lag continues?

1 Like

I know the problem to the AI, its constantly sending new paths which lag the game. Im just looking for a way to fix it

1 Like