Pathfinding from editor scripts

This page shows how to get pathfinding working outside of play mode from e.g an editor script.

Pathfinding in editor mode, i.e when the game is not running at all in the Unity editor works in the same way as in play mode with the only major difference being that path requests are synchronous, i.e they will be calculated immediately. Normally path requests are asynchronous and may take several frames to calculate.

To get it working you must however first initialize the pathfinding system because in editor mode graphs may not have been deserialized and the graphs may not be scanned. The AstarPath.FindAstarPath method will make sure that the AstarPath.active property is set and that all graphs have been deserialized (they are stored as a byte array internally).

// Make sure the AstarPath object has been loaded
AstarPath.FindAstarPath();

AstarPath.active.Scan();
If you think a graph might have been scanned, but you are not sure (for example you might run a particular editor script several times) then you can check first. A good indicator is if the graph has any nodes.

// Check if the first grid graph in the scene has any nodes
// if it doesn't then it is not scanned.
if (AstarPath.active.data.gridGraph.nodes == null) AstarPath.active.Scan();
After this you can request paths as usual. The example below uses the AstarPath component directly, but using a Seeker component should work just as well. ABPath path = ABPath.Construct(transform.position, target.position);
AstarPath.StartPath(path);
// Everything is synchronous so the path is calculated now

Debug.Log("Found a path with " + path.vectorPath.Count + " points. The error log says: " + path.errorLog);

// Draw the path in the scene view
for (int i = 0; i < path.vectorPath.Count - 1; i++) {
Debug.DrawLine(path.vectorPath[i], path.vectorPath[i+1], Color.red);
}