When dealing with large graphs, computing paths can take a lot of time, even halting the game for a couple of seconds. This could ruins its overall experience, to say the least. Luckily enough there are methods to avoid this.
We'll learn how to implement path-finding techniques using coroutines by refactoring the A* algorithm learned previously, but we will handle its signature as a different function.
Even though this recipe is only defining a function, please take into consideration the comments in the code to understand the indentation and code flow more effectively:
Graph
class and add a couple of member variables. One for storing the path and the other to know whether the coroutine has finished:public List<Vertex> path; public bool isFinished;
public IEnumerator GetPathInFrames(GameObject srcObj, GameObject dstObj, Heuristic h = null) { //next steps }
isFinished = false; path = new List<Vertex>(); if (srcObj == null || dstObj == null) { path = new List<Vertex>(); isFinished = true; yield break; }
while (frontier.Count != 0)
{
// changes over A*
yield return null;
//////////////////////////////
node = frontier.Remove();
if (ReferenceEquals(node.vertex, dst)) { // changes over A* path = BuildPath(src.id, node.vertex.id, ref previous); break; ////////////////////////////// }
isFinished = true; yield break;
The yield return null statement inside the main loop works as a flag for delivering control to the higher-level functions, thus computing each new loop in each new frame using Unity's internal multi-tasking system.