How do I cancel a path find

How do I over write a current ongoing path find (using pathfinding service), whenever a new path find is created.

Example: How do I make it so if the player clicks twice it will cancel the first pathfind.

if Input.UserInputType == Enum.UserInputType.MouseButton1 and not X then
			
			local Path = Pathfinding:CreatePath()
			Path:ComputeAsync(RootPart.Position, Mouse.Hit.Position)
			local Waypoints = Path:GetWaypoints()
			
			
			for i, Waypoint in pairs(Waypoints) do
				print(Waypoint)
				Humanoid:MoveTo(Waypoint.Position)
				Humanoid.MoveToFinished:Wait()
			end
		end
1 Like

I would think you could use an ID system to describe which pathfinding process is active. Any pathfinding processes with the wrong active id will just break the loop.

-- outside the user input binding,
local activeID -- signifies the current active pathfinding process

-- in the code you posted
			activeID = newproxy() -- the active process has changed
			local currentID = activeID -- make this the active process

			local Path = Pathfinding:CreatePath()
			Path:ComputeAsync(RootPart.Position, Mouse.Hit.Position)
			local Waypoints = Path:GetWaypoints()
			
			
			for i, Waypoint in Waypoints do
				print(Waypoint)
				Humanoid:MoveTo(Waypoint.Position)
				Humanoid.MoveToFinished:Wait()

				-- if the process doesn't match active process,
				if activeID ~= currentID then 
					break -- stop pathfinding
				end
			end

In theory, doing another pathfinding process would cancel the first one because the id would be updated and wouldn’t match anymore. Let me know if anything goes wrong!

Edit: alternative method

Another more literal way to go about it is to get the current thread and compare it to the active thread.

-- outside the user input binding,
local activeThread

-- in the code you posted
			activeThread = coroutine.running()
			local currentThread = activeThread

			local Path = Pathfinding:CreatePath()
			Path:ComputeAsync(RootPart.Position, Mouse.Hit.Position)
			local Waypoints = Path:GetWaypoints()
			
			
			for i, Waypoint in Waypoints do
				print(Waypoint)
				Humanoid:MoveTo(Waypoint.Position)
				Humanoid.MoveToFinished:Wait()

				-- if the process doesn't match active process,
				if activeThread ~= currentThread then 
					break -- stop pathfinding
				end
			end
11 Likes

The first method seems to have worked very well, thank you very much this has been puzzling me for a while now.

1 Like

what do you put in currentID???

thank you so much (ipso ipso carrot carrot :sob: )