Support Forum

Fastest way to know the shortest path between multiple targets?

I’m on an auto battler game, trying to improve my retargeting system.
My idea was that when the current target is gets out of attack range, I would check vetween all other units which one is the fastest to walk to.

So I get a list of all my possible targets (might filter on a limit distance), generate a path to every one with seeker.StartPath(), waitForPath and GetTotalLength. I store the lengths in a list and send it through an event to my unit.Preformatted text

Problem is this takes a few frames per unit to get the result back, so if I have 15 targets in my scene it could be up to maybe a second before I know who I should be heading to.

And I have to do this every time a target moves out of range, for every unit (allies and ennemies).

I bet there is a better way to do this, just did not find it yet

public IEnumerator TestGetPathLength(Units[] endPositions)
	print("in pathfinding");
	List<(Units, float)> unitsDistances = new List<(Units, float)>();
	foreach (var endPosition in endPositions)
		print($"StartPath : {framesCount} frames");
		Path p = seeker.StartPath(transform.position, endPosition.transform.position);
		yield return p.WaitForPath();
		float length = p.GetTotalLength();
		unitsDistances.Add((endPosition, length));
		print($"PathLength : {length}, {framesCount} frames");

Edit : After more testings, it is nowhere near a second, so I could be fine with this solution, but is there another way to actually get a possible path length in realtime without a callback / coroutine?


You can use MultiTargetPath - A* Pathfinding Project

Thank you, I will try with this!