How to do it...

Even though this recipe is only defining a function, please take into consideration the comments in the code for better understanding of the implementation and code flow:

  1. Declare the GetPathBFS function:
public List<Vertex> GetPathBFS(GameObject srcObj, GameObject dstObj) 
{ 
    if (srcObj == null || dstObj == null) 
        return new List<Vertex>(); 
    // next steps 
}

  1. Declare and initialize the variables we need for the algorithm:
Vertex[] neighbours; 
Queue<Vertex> q = new Queue<Vertex>(); 
Vertex src = GetNearestVertex(srcObj.transform.position); 
Vertex dst = GetNearestVertex(dstObj.transform.position); 
Vertex v; 
int[] previous = new int[vertices.Count]; 
for (int i = 0; i < previous.Length; i++) 
    previous[i] = -1; 
previous[src.id] = src.id; 
q.Enqueue(src); 
  1. Implement the BFS algorithm for finding a path:
while (q.Count != 0) 
{ 
    v = q.Dequeue(); 
    if (ReferenceEquals(v, dst)) 
    { 
        return BuildPath(src.id, v.id, ref previous); 
    } 
 
    neighbours = GetNeighbours(v); 
    foreach (Vertex n in neighbours) 
    { 
        if (previous[n.id] != -1) 
            continue; 
        previous[n.id] = v.id; 
        q.Enqueue(n); 
    } 
} 
return new List<Vertex>();