A* Pathfinding Project  3.8.12
The A* Pathfinding Project for Unity 3D
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Properties Events Macros Groups Pages
AstarPath Class Reference

Core Component for the A* Pathfinding System. More...

Detailed Description

Core Component for the A* Pathfinding System.

This class handles all of the pathfinding system, calculates all paths and stores the info.
This class is a singleton class, meaning there should only exist at most one active instance of it in the scene.
It might be a bit hard to use directly, usually interfacing with the pathfinding system is done through the Seeker class.

Examples:
MovePointNode.cs, MultiTargetFree.cs, and WaypointPath.cs.

Classes

struct  AstarWorkItem
 
struct  GUOSingle
 Holds a single update that needs to be performed on a graph. More...
 

Public Types

enum  AstarDistribution { WebsiteDownload, AssetStore }
 Information about where the package was downloaded. More...
 

Public Member Functions

void AddWorkItem (AstarWorkItem itm)
 Add a work item to be processed when pathfinding is paused.
 
void BlockUntilPathQueueBlocked ()
 Blocks until all pathfinding threads are paused and blocked.
 
void DestroyNode (GraphNode node)
 Destroyes the given node.
 
void EnsureValidFloodFill ()
 If a WorkItem needs to have a valid flood fill during execution, call this method to ensure there are no pending flood fills.
 
void FloodFill (GraphNode seed)
 Floodfills starting from the specified node.
 
void FloodFill (GraphNode seed, uint area)
 Floodfills starting from 'seed' using the specified area.
 
void FloodFill ()
 Floodfills all graphs and updates areas for every node.
 
void FlushGraphUpdates ()
 Forces graph updates to complete in a single frame.
 
void FlushThreadSafeCallbacks ()
 Forces thread safe callbacks to run.
 
void FlushWorkItems ()
 Forces work items to complete in a single frame.
 
void FlushWorkItems (bool unblockOnComplete, bool block)
 Make sure work items are executed.
 
NNInfo GetNearest (Vector3 position)
 Returns the nearest node to a position using the specified NNConstraint.
 
NNInfo GetNearest (Vector3 position, NNConstraint constraint)
 Returns the nearest node to a position using the specified NNConstraint.
 
NNInfo GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint)
 Returns the nearest node to a position using the specified NNConstraint.
 
GraphNode GetNearest (Ray ray)
 Returns the node closest to the ray (slow).
 
int GetNewNodeIndex ()
 Returns a new global node index.
 
ushort GetNextPathID ()
 Returns the next free path ID.
 
string[] GetTagNames ()
 Returns tag names.
 
void InitializeNode (GraphNode node)
 Initializes temporary path data for a node.
 
void LogProfiler ()
 
void OnApplicationQuit ()
 Terminates pathfinding threads when the application quits.
 
void QueueGraphUpdates ()
 Will apply queued graph updates as soon as possible, regardless of batchGraphUpdates.
 
void QueueWorkItemFloodFill ()
 Call during work items to queue a flood fill.
 
void ResetProfiler ()
 
void ReturnPaths (bool timeSlice)
 Returns all paths in the return stack.
 
void Scan ()
 Scans all graphs.
 
void ScanLoop (OnScanStatus statusCallback)
 Scans all graphs.
 
void SetUpReferences ()
 Internal method to make sure active is set to this object and that astarData is not null.
 
void UpdateGraphs (Bounds bounds, float t)
 Update all graphs within bounds after t seconds.
 
void UpdateGraphs (GraphUpdateObject ob, float t)
 Update all graphs using the GraphUpdateObject after t seconds.
 
void UpdateGraphs (Bounds bounds)
 Update all graphs within bounds.
 
void UpdateGraphs (GraphUpdateObject ob)
 Update all graphs using the GraphUpdateObject.
 

Static Public Member Functions

static int CalculateThreadCount (ThreadCount count)
 Calculates number of threads to use.
 
static string[] FindTagNames ()
 Tries to find an AstarPath object and return tag names.
 
static void RegisterSafeUpdate (System.Action callback, bool threadSafe)
 Will send a callback when it is safe to update nodes.
 
static void RegisterSafeUpdate (System.Action callback)
 Will send a callback when it is safe to update nodes.
 
static void StartPath (Path p, bool pushToFront=false)
 Puts the Path in queue for calculation.
 
static void WaitForPath (Path p)
 Wait for the specified path to be calculated.
 

Public Attributes

AstarData astarData
 Holds all graph data.
 
EuclideanEmbedding euclideanEmbedding = new EuclideanEmbedding()
 Holds settings for heuristic optimization.
 
uint lastUniqueAreaIndex = 0
 The last area index which was used.
 
bool showGraphs = false
 Shows or hides graph inspectors.
 

Static Public Attributes

static AstarPath active
 Returns the active AstarPath object in the scene.
 
static readonly string Branch = "master_Free"
 Which branch of the A* Pathfinding Project is this release.
 
static readonly AstarDistribution Distribution = AstarDistribution.WebsiteDownload
 Used by the editor to guide the user to the correct place to download updates.
 
static bool isEditor = true
 

Package Functions

void FlushWorkItemsInternal (bool unblockOnComplete)
 Make sure work items are executed.
 
void VerifyIntegrity ()
 Does simple error checking.
 

Properties

NavGraph[] graphs [get, set]
 Shortcut to Pathfinding.AstarData.graphs.
 
System.Type[] graphTypes [get]
 See Pathfinding.AstarData.
 
bool IsAnyGraphUpdatesQueued [get]
 Returns if any graph updates are waiting to be applied.
 
bool isScanning [get, set]
 Set when scanning is being done.
 
static bool IsUsingMultithreading [get]
 Returns whether or not multithreading is used.
 
static int NumParallelThreads [get]
 Number of parallel pathfinders.
 
static System.Version Version [get]
 The version number for the A* Pathfinding Project.
 

Private Types

enum  GraphUpdateOrder { GraphUpdate, FloodFill }
 Order type for updating graphs. More...
 

Private Member Functions

void Awake ()
 Sets up all needed variables and scans the graphs.
 
IEnumerator DelayedGraphUpdate ()
 Waits a moment with updating graphs.
 
bool DrawUnwalkableNode (GraphNode node)
 Draws a cube at the node's position if unwalkable.
 
void Initialize ()
 Initializes various variables.
 
void InterruptPathfinding ()
 Blocks the path queue so that e.g work items can be performed.
 
void LogPathResults (Path p)
 Prints path results to the log.
 
void OnDestroy ()
 Clears up variables and other stuff, destroys graphs.
 
void OnDisable ()
 Cleans up meshes to avoid memory leaks.
 
void OnDrawGizmos ()
 Calls OnDrawGizmos on graph generators and also OnDrawGizmosCallback.
 
void OnGUI ()
 Draws the InGame debugging (if enabled), also shows the fps if 'L' is pressed down.
 
void PerformBlockingActions (bool force=false, bool unblockOnComplete=true)
 
bool ProcessGraphUpdates (bool force)
 Updates graphs.
 
void ProcessGraphUpdatesAsync (System.Object _astar)
 Graph update thread.
 
int ProcessWorkItems (bool force)
 Process graph updating work items.
 
void QueueGraphUpdatesInternal ()
 Schedules graph updates internally.
 
void Update ()
 
IEnumerator UpdateGraphsInteral (GraphUpdateObject ob, float t)
 Update all graphs using the GraphUpdateObject after t seconds.
 

Static Private Member Functions

static void AstarLog (string s)
 Logs a string while taking into account logPathResults.
 
static void AstarLogError (string s)
 Logs an error string while taking into account logPathResults.
 
static IEnumerator CalculatePaths (System.Object _threadInfo)
 Main pathfinding method.
 
static void CalculatePathsThreaded (System.Object _threadInfo)
 Main pathfinding method (multithreaded).
 

Private Attributes

Stack< GraphNodefloodStack
 Stack used for flood-filling the graph.
 
System.Threading.AutoResetEvent graphUpdateAsyncEvent = new System.Threading.AutoResetEvent(false)
 
Queue< GraphUpdateObjectgraphUpdateQueue
 Stack containing all waiting graph update queries.
 
Queue< GUOSinglegraphUpdateQueueAsync = new Queue<GUOSingle>()
 Queue of all async graph updates waiting to be executed.
 
Queue< GUOSinglegraphUpdateQueueRegular = new Queue<GUOSingle>()
 Queue of all non-async graph updates waiting to be executed.
 
bool graphUpdateRoutineRunning = false
 
Thread graphUpdateThread
 Reference to the thread which handles async graph updates.
 
bool isRegisteredForUpdate = false
 Makes sure QueueGraphUpdates will not queue multiple graph update orders.
 
float lastGraphUpdate = -9999F
 Time the last graph update was done.
 
ushort nextFreePathID = 1
 The next unused Path ID.
 
int nextNodeIndex = 1
 Holds the next node index which has not been used by any previous node.
 
Stack< int > nodeIndexPool = new Stack<int>()
 Holds indices for nodes that have been destroyed.
 
ThreadControlQueue pathQueue = new ThreadControlQueue(0)
 Holds all paths waiting to be calculated.
 
Path pathReturnPop
 A temporary queue for paths which weren't returned due to large processing time.
 
System.Threading.ManualResetEvent processingGraphUpdatesAsync = new System.Threading.ManualResetEvent(true)
 
bool processingWorkItems = false
 
bool queuedWorkItemFloodFill = false
 True if any work items have queued a flood fill.
 
Queue< AstarWorkItemworkItems = new Queue<AstarWorkItem>()
 
bool workItemsQueued = false
 True if any work items are currently queued.
 

Static Private Attributes

static
Pathfinding.Util.LockFreeStack 
pathReturnStack = new Pathfinding.Util.LockFreeStack()
 Holds all paths which are waiting to be flagged as completed.
 
static readonly System.Object safeUpdateLock = new object()
 
static IEnumerator threadEnumerator
 When no multithreading is used, the IEnumerator is stored here.
 
static PathThreadInfo[] threadInfos = new PathThreadInfo[0]
 Holds info about each thread.
 
static Thread[] threads
 References to each of the pathfinding threads.
 
static int waitForPathDepth = 0
 

Inspector - Debug

bool showNavGraphs = true
 Toggle for showing the gizmo debugging for the graphs in the scene view (editor only).
 
bool showUnwalkableNodes = true
 Toggle to show unwalkable nodes.
 
GraphDebugMode debugMode
 The mode to use for drawing nodes in the sceneview.
 
float debugFloor = 0
 Low value to use for certain debugMode modes.
 
float debugRoof = 20000
 High value to use for certain debugMode modes.
 
bool manualDebugFloorRoof = false
 If set, the debugFloor and debugRoof values will not be automatically recalculated.
 
bool showSearchTree = false
 If enabled, nodes will draw a line to their 'parent'.
 
float unwalkableNodeDebugSize = 0.3F
 Size of the red cubes shown in place of unwalkable nodes.
 
PathLog logPathResults = PathLog.Normal
 The amount of debugging messages.
 

Inspector - Settings

float maxNearestNodeDistanceSqr [get]
 Max Nearest Node Distance Squared.
 
bool limitGraphUpdates [get, set]
 Batch graph updates.
 
float maxGraphUpdateFreq [get, set]
 Limit for how often should graphs be updated.
 
float maxNearestNodeDistance = 100
 Max Nearest Node Distance.
 
bool scanOnStartup = true
 If true, all graphs will be scanned in Awake.
 
bool fullGetNearestSearch = false
 Do a full GetNearest search for all graphs.
 
bool prioritizeGraphs = false
 Prioritize graphs.
 
float prioritizeGraphsLimit = 1F
 Distance limit for prioritizeGraphs.
 
AstarColor colorSettings
 Reference to the color settings for this AstarPath object.
 
Heuristic heuristic = Heuristic.Euclidean
 The heuristic to use.
 
float heuristicScale = 1F
 The scale of the heuristic.
 
ThreadCount threadCount = ThreadCount.None
 Number of pathfinding threads to use.
 
float maxFrameTime = 1F
 Max number of milliseconds to spend each frame for pathfinding.
 
int minAreaSize = 0
 Defines the minimum amount of nodes in an area.
 
bool batchGraphUpdates = false
 Throttle graph updates and batch them to improve performance.
 
float graphUpdateBatchingInterval = 0.2F
 How often should graphs be updated.
 
string[] tagNames = null
 Stored tag names.
 

Debug Members

PathHandler debugPathData [get]
 NodeRunData from debugPath.
 
float lastScanTime = 0F
 The time it took for the last call to Scan() to complete.
 
Path debugPath
 The path to debug using gizmos.
 
string inGameDebugPath
 Debug string from the last completed path.
 

Callbacks

static System.Action OnAwakeSettings
 Called on Awake before anything else is done.
 
static OnGraphDelegate OnGraphPreScan
 Called for each graph before they are scanned.
 
static OnGraphDelegate OnGraphPostScan
 Called for each graph after they have been scanned.
 
static OnPathDelegate OnPathPreSearch
 Called for each path before searching.
 
static OnPathDelegate OnPathPostSearch
 Called for each path after searching.
 
static OnScanDelegate OnPreScan
 Called before starting the scanning.
 
static OnScanDelegate OnPostScan
 Called after scanning.
 
static OnScanDelegate OnLatePostScan
 Called after scanning has completed fully.
 
static OnScanDelegate OnGraphsUpdated
 Called when any graphs are updated.
 
static System.Action On65KOverflow
 Called when pathID overflows 65536 and resets back to zero.
 
System.Action OnDrawGizmosCallback
 Used internally to enable gizmos in editor scripts.
 
System.Action OnUnloadGizmoMeshes
 Used internally to unload temporary meshes in the editor.
 
System.Action OnGraphsWillBeUpdated
 
System.Action OnGraphsWillBeUpdated2
 
static System.Action OnThreadSafeCallback
 Will send a callback when it is safe to update the nodes.
 

Member Enumeration Documentation

Information about where the package was downloaded.

Enumerator:
WebsiteDownload 
AssetStore 
enum GraphUpdateOrder
private

Order type for updating graphs.

Enumerator:
GraphUpdate 
FloodFill 

Member Function Documentation

void AddWorkItem ( AstarWorkItem  itm)

Add a work item to be processed when pathfinding is paused.

See Also
ProcessWorkItems
static void AstarLog ( string  s)
staticprivate

Logs a string while taking into account logPathResults.

static void AstarLogError ( string  s)
staticprivate

Logs an error string while taking into account logPathResults.

void Awake ( )
private

Sets up all needed variables and scans the graphs.

Calls Initialize, starts the ReturnPaths coroutine and scans all graphs. Also starts threads if using multithreading

See Also
OnAwakeSettings
void BlockUntilPathQueueBlocked ( )

Blocks until all pathfinding threads are paused and blocked.

A call to pathQueue.Unblock is required to resume pathfinding calculations. However in most cases you should never unblock the path queue, instead let the pathfinding scripts do that in the next update. Unblocking the queue when other tasks (e.g graph updates) are running can interfere and cause invalid graphs.

Note
In most cases this should not be called from user code.
static IEnumerator CalculatePaths ( System.Object  _threadInfo)
staticprivate

Main pathfinding method.

This method will calculate the paths in the pathfinding queue.

See Also
CalculatePathsThreaded
StartPath
static void CalculatePathsThreaded ( System.Object  _threadInfo)
staticprivate

Main pathfinding method (multithreaded).

This method will calculate the paths in the pathfinding queue when multithreading is enabled.

See Also
CalculatePaths
StartPath
A* Pro Feature:
This is an A* Pathfinding Project Pro feature only. This function/class/variable might not exist in the Free version of the A* Pathfinding Project or the functionality might be limited
The Pro version can be bought here
static int CalculateThreadCount ( ThreadCount  count)
static

Calculates number of threads to use.

If count is not Automatic, simply returns count casted to an int.

Returns
An int specifying how many threads to use, 0 means a coroutine should be used for pathfinding instead of a separate thread.

If count is set to Automatic it will return a value based on the number of processors and memory for the current system. If memory is <= 512MB or logical cores are <= 1, it will return 0. If memory is <= 1024 it will clamp threads to max 2. Otherwise it will return the number of logical cores clamped to 6.

When running on WebGL this method always returns 0

IEnumerator DelayedGraphUpdate ( )
private

Waits a moment with updating graphs.

If batchGraphUpdates is set, we want to keep some space between them to let pathfinding threads running and then calculate all queued calls at once

void DestroyNode ( GraphNode  node)

Destroyes the given node.

This is to be called after the node has been disconnected from the graph so that it cannot be reached from any other nodes. It should only be called during graph updates, that is when the pathfinding threads are either not running or paused.

Warning
This method should not be called by user code. It is used internally by the system.
bool DrawUnwalkableNode ( GraphNode  node)
private

Draws a cube at the node's position if unwalkable.

Used for gizmo drawing

void EnsureValidFloodFill ( )

If a WorkItem needs to have a valid flood fill during execution, call this method to ensure there are no pending flood fills.

static string [] FindTagNames ( )
static

Tries to find an AstarPath object and return tag names.

If an AstarPath object cannot be found, it returns an array of length 1 with an error message.

See Also
AstarPath.GetTagNames
void FloodFill ( GraphNode  seed)

Floodfills starting from the specified node.

void FloodFill ( GraphNode  seed,
uint  area 
)

Floodfills starting from 'seed' using the specified area.

void FloodFill ( )

Floodfills all graphs and updates areas for every node.

The different colored areas that you see in the scene view when looking at graphs are called just 'areas', this method calculates which nodes are in what areas.

See Also
Pathfinding.Node.area
void FlushGraphUpdates ( )

Forces graph updates to complete in a single frame.

This will force the pathfinding threads to finish calculate the path they are currently calculating (if any) and then pause. When all threads have paused, graph updates will be performed.

Warning
Using this very often (many times per second) can reduce your fps due to a lot of threads waiting for one another. But you probably wont have to worry about that.
Note
This is almost identical to FlushWorkItems, but added for more descriptive name. This function will also override any time limit delays for graph updates. This is because graph updates are implemented using work items. So calling this function will also call other thread safe callbacks (if any are waiting).

Will not do anything if there are no graph updates queued (not even call other callbacks).

void FlushThreadSafeCallbacks ( )

Forces thread safe callbacks to run.

This will force all thread safe callbacks to run immidiately. Or rather, it will block the Unity main thread until callbacks can be called and then issue them. This will force the pathfinding threads to finish calculate the path they are currently calculating (if any) and then pause. When all threads have paused, thread safe callbacks will be called (which can be e.g graph updates).

Warning
Using this very often (many times per second) can reduce your fps due to a lot of threads waiting for one another. But you probably wont have to worry about that
Note
This is almost (note almost) identical to FlushGraphUpdates, but added for more descriptive name.

Will not do anything if there are no thread safe callbacks waiting to run.

void FlushWorkItems ( )

Forces work items to complete in a single frame.

void FlushWorkItems ( bool  unblockOnComplete,
bool  block 
)

Make sure work items are executed.

Parameters
unblockOnCompleteIf true, pathfinding will be allowed to start running immediately after completing all work items.
blockIf true, work items that take more than one frame to complete will be force to complete during this call. If false, then after this call there might still be work left to do.
See Also
AddWorkItem
Deprecated:
Use FlushWorkItems() instead or use FlushWorkItemsInternal if you really need to.
void FlushWorkItemsInternal ( bool  unblockOnComplete)
package

Make sure work items are executed.

Parameters
unblockOnCompleteIf true, pathfinding will be allowed to start running immediately after completing all work items.
Warning
This is an internal method. Unless you have a very good reason, you should probably not call it.
See Also
AddWorkItem
NNInfo GetNearest ( Vector3  position)

Returns the nearest node to a position using the specified NNConstraint.

Searches through all graphs for their nearest nodes to the specified position and picks the closest one.
Using the NNConstraint.None constraint.

See Also
Pathfinding.NNConstraint
NNInfo GetNearest ( Vector3  position,
NNConstraint  constraint 
)

Returns the nearest node to a position using the specified NNConstraint.

Searches through all graphs for their nearest nodes to the specified position and picks the closest one. The NNConstraint can be used to specify constraints on which nodes can be chosen such as only picking walkable nodes.

See Also
Pathfinding.NNConstraint
NNInfo GetNearest ( Vector3  position,
NNConstraint  constraint,
GraphNode  hint 
)

Returns the nearest node to a position using the specified NNConstraint.

Searches through all graphs for their nearest nodes to the specified position and picks the closest one. The NNConstraint can be used to specify constraints on which nodes can be chosen such as only picking walkable nodes.

See Also
Pathfinding.NNConstraint
GraphNode GetNearest ( Ray  ray)

Returns the node closest to the ray (slow).

Warning
This function is brute-force and very slow, use with caution
int GetNewNodeIndex ( )

Returns a new global node index.

Warning
This method should not be called directly. It is used by the GraphNode constructor.
ushort GetNextPathID ( )

Returns the next free path ID.

string [] GetTagNames ( )

Returns tag names.

Makes sure that the tag names array is not null and of length 32. If it is null or not of length 32, it creates a new array and fills it with 0,1,2,3,4 etc...

See Also
AstarPath.FindTagNames
void Initialize ( )
private

Initializes various variables.

Sets up references , Searches for graph types, calls Awake on astarData and on all graphs

See Also
AstarData.FindGraphTypes
SetUpReferences
void InitializeNode ( GraphNode  node)

Initializes temporary path data for a node.

Warning
This method should not be called directly. It is used by the GraphNode constructor.
void InterruptPathfinding ( )
private

Blocks the path queue so that e.g work items can be performed.

void LogPathResults ( Path  p)
private

Prints path results to the log.

What it prints can be controled using logPathResults.

See Also
logPathResults
PathLog
Pathfinding.Path.DebugString
void LogProfiler ( )
void OnApplicationQuit ( )

Terminates pathfinding threads when the application quits.

void OnDestroy ( )
private

Clears up variables and other stuff, destroys graphs.

Note that when destroying an AstarPath object, all static variables such as callbacks will be cleared.

void OnDisable ( )
private

Cleans up meshes to avoid memory leaks.

void OnDrawGizmos ( )
private

Calls OnDrawGizmos on graph generators and also OnDrawGizmosCallback.

void OnGUI ( )
private

Draws the InGame debugging (if enabled), also shows the fps if 'L' is pressed down.

See Also
logPathResults PathLog
void PerformBlockingActions ( bool  force = false,
bool  unblockOnComplete = true 
)
private
bool ProcessGraphUpdates ( bool  force)
private

Updates graphs.

Will do some graph updates, possibly signal another thread to do them. Will only process graph updates added by QueueGraphUpdatesInternal

Parameters
forceIf true, all graph updates will be processed before this function returns. The return value will be True.
Returns
True if all graph updates have been done and pathfinding (or other tasks) may resume. False if there are still graph updates being done or waiting in the queue.
void ProcessGraphUpdatesAsync ( System.Object  _astar)
private

Graph update thread.

Async graph updates will be executed by this method in another thread.

int ProcessWorkItems ( bool  force)
private

Process graph updating work items.

Process all queued work items, e.g graph updates and the likes.

Returns
  • 0 if there were no work items to be processed or if nothing can be done because pathfinding is not paused.
  • 1 if there are still items to be processed.
  • 2 if the last work items was processed and pathfinding threads are ready to be resumed.
See Also
AddWorkItem
threadSafeUpdateState
Update
void QueueGraphUpdates ( )

Will apply queued graph updates as soon as possible, regardless of batchGraphUpdates.

Calling this multiple times will not create multiple callbacks. Makes sure DoUpdateGraphs is called as soon as possible.
This function is useful if you are limiting graph updates, but you want a specific graph update to be applied as soon as possible regardless of the time limit.

See Also
FlushGraphUpdates
void QueueGraphUpdatesInternal ( )
private

Schedules graph updates internally.

void QueueWorkItemFloodFill ( )

Call during work items to queue a flood fill.

An instant flood fill can be done via FloodFill() but this method can be used to batch several updates into one to increase performance. WorkItems which require a valid Flood Fill in their execution can call EnsureValidFloodFill to ensure that a flood fill is done if any earlier work items queued one.

Once a flood fill is queued it will be done after all WorkItems have been executed.

static void RegisterSafeUpdate ( System.Action  callback,
bool  threadSafe 
)
static

Will send a callback when it is safe to update nodes.

This is defined as between the path searches. This callback will only be sent once and is nulled directly after the callback has been sent. When using more threads than one, calling this often might decrease pathfinding performance due to a lot of idling in the threads. Not performance as in it will use much CPU power, but performance as in the number of paths per second will probably go down (though your framerate might actually increase a tiny bit)

You should only call this function from the main unity thread (i.e normal game code).

Note
The threadSafe parameter has been deprecated
Deprecated:
Examples:
MovePointNode.cs.
static void RegisterSafeUpdate ( System.Action  callback)
static

Will send a callback when it is safe to update nodes.

This is defined as between the path searches. This callback will only be sent once and is nulled directly after the callback has been sent. When using more threads than one, calling this often might decrease pathfinding performance due to a lot of idling in the threads. Not performance as in it will use much CPU power, but performance as in the number of paths per second will probably go down (though your framerate might actually increase a tiny bit)

You should only call this function from the main unity thread (i.e normal game code).

var node = AstarPath.active.GetNearest (transform.position).node;
node.walkable = false;
});
var node = AstarPath.active.GetNearest (transform.position).node;
node.position = (Int3)transform.position;
});
void ResetProfiler ( )
void ReturnPaths ( bool  timeSlice)

Returns all paths in the return stack.

Paths which have been processed are put in the return stack. This function will pop all items from the stack and return them to e.g the Seeker requesting them.

Parameters
timeSliceDo not return all paths at once if it takes a long time, instead return some and wait until the next call.
void Scan ( )

Scans all graphs.

Calling this method will recalculate all graphs in the scene. This method is pretty slow (depending on graph type and graph complexity of course), so it is advisable to use smaller graph updates whenever possible.

See Also
graph-updates
void ScanLoop ( OnScanStatus  statusCallback)

Scans all graphs.

This is a IEnumerable, you can loop through it to get the progress

foreach (Progress progress in AstarPath.active.ScanLoop ()) {
Debug.Log ("Scanning... " + progress.description + " - " + (progress.progress*100).ToString ("0") + "%");
}
See Also
Scan
void SetUpReferences ( )

Internal method to make sure active is set to this object and that astarData is not null.

Also calls OnEnable for the colorSettings and initializes astarData.userConnections if it wasn't initialized before

Note
This is mostly for use internally by the system.
static void StartPath ( Path  p,
bool  pushToFront = false 
)
static

Puts the Path in queue for calculation.

The callback specified when constructing the path will be called when the path has been calculated. Usually you should use the Seeker component instead of calling this function directly.

Parameters
pThe path that should be put in queue for calculation
pushToFrontIf true, the path will be pushed to the front of the queue, bypassing all waiting paths and making it the next path to be calculated. This can be useful if you have a path which you want to prioritize over all others. Be careful to not overuse it though. If too many paths are put in the front of the queue often, this can lead to normal paths having to wait a very long time before being calculated.
Examples:
MultiTargetFree.cs, and WaypointPath.cs.
void Update ( )
private
void UpdateGraphs ( Bounds  bounds,
float  t 
)

Update all graphs within bounds after t seconds.

This function will add a GraphUpdateObject to the graphUpdateQueue. The graphs will be updated as soon as possible.

void UpdateGraphs ( GraphUpdateObject  ob,
float  t 
)

Update all graphs using the GraphUpdateObject after t seconds.

This can be used to, e.g make all nodes in an area unwalkable, or set them to a higher penalty.

void UpdateGraphs ( Bounds  bounds)

Update all graphs within bounds.

This function will add a GraphUpdateObject to the graphUpdateQueue. The graphs will be updated as soon as possible.

This is equivalent to
UpdateGraphs (new GraphUpdateObject (bounds))

See Also
FlushGraphUpdates
void UpdateGraphs ( GraphUpdateObject  ob)

Update all graphs using the GraphUpdateObject.

This can be used to, e.g make all nodes in an area unwalkable, or set them to a higher penalty. The graphs will be updated as soon as possible (with respect to batchGraphUpdates)

See Also
FlushGraphUpdates
IEnumerator UpdateGraphsInteral ( GraphUpdateObject  ob,
float  t 
)
private

Update all graphs using the GraphUpdateObject after t seconds.

void VerifyIntegrity ( )
package

Does simple error checking.

static void WaitForPath ( Path  p)
static

Wait for the specified path to be calculated.

Normally it takes a few frames for a path to get calculated and returned. This function will ensure that the path will be calculated when this function returns and that the callback for that path has been called.

Note
Do not confuse this with Pathfinding.Path.WaitForPath. This one will halt all operations until the path has been calculated while Pathfinding.Path.WaitForPath will wait using yield until it has been calculated.

If requesting a lot of paths in one go and waiting for the last one to complete, it will calculate most of the paths in the queue (only most if using multithreading, all if not using multithreading).

Use this function only if you really need to. There is a point to spreading path calculations out over several frames. It smoothes out the framerate and makes sure requesting a large number of paths at the same time does not cause lag.

Note
Graph updates and other callbacks might get called during the execution of this function.

When the pathfinder is shutting down. I.e in OnDestroy, this function will not do anything.

Parameters
pThe path to wait for. The path must be started, otherwise an exception will be thrown.
Exceptions
Exceptionif pathfinding is not initialized properly for this scene (most likely no AstarPath object exists) or if the path has not been started yet. Also throws an exception if critical errors occur such as when the pathfinding threads have crashed (which should not happen in normal cases). This prevents an infinite loop while waiting for the path.
See Also
Pathfinding.Path.WaitForPath

Member Data Documentation

AstarPath active
static

Returns the active AstarPath object in the scene.

Note
This is only set if the AstarPath object has been initialized (which happens in Awake).
AstarData astarData

Holds all graph data.

bool batchGraphUpdates = false

Throttle graph updates and batch them to improve performance.

If toggled, graph updates will batched and executed less often (specified by graphUpdateBatchingInterval).

This can have a positive impact on pathfinding throughput since the pathfinding threads do not need to be stopped as often, and it reduces the overhead per graph update. All graph updates are still applied however, they are just batched together so that more of them are applied at the same time.

However do not use this if you want minimal latency between a graph update being requested and it being applied. This only applies to graph updates requested using the UpdateGraphs method. Not those requested using RegisterSafeUpdate or AddWorkItem.

readonly string Branch = "master_Free"
static

Which branch of the A* Pathfinding Project is this release.

Used when checking for updates so that users of the development versions can get notifications of development updates.

AstarColor colorSettings

Reference to the color settings for this AstarPath object.

Color settings include for example which color the nodes should be in, in the sceneview.

float debugFloor = 0

Low value to use for certain debugMode modes.

For example if debugMode is set to G, this value will determine when the node will be totally red.

Note
Only relevant in the editor
See Also
debugRoof
GraphDebugMode debugMode

The mode to use for drawing nodes in the sceneview.

Note
Only relevant in the editor
See Also
Pathfinding.GraphDebugMode
Path debugPath

The path to debug using gizmos.

This is equal to the last path which was calculated. It is used in the editor to draw debug information using gizmos.

float debugRoof = 20000

High value to use for certain debugMode modes.

For example if debugMode is set to G, this value will determine when the node will be totally green.

For the penalty debug mode, the nodes will be colored green when they have a penalty of zero and red when their penalty is greater or equal to this value and something between red and green for values in between.

Note
Only relevant in the editor
See Also
debugFloor
readonly AstarDistribution Distribution = AstarDistribution.WebsiteDownload
static

Used by the editor to guide the user to the correct place to download updates.

EuclideanEmbedding euclideanEmbedding = new EuclideanEmbedding()

Holds settings for heuristic optimization.

See Also
heuristic-opt
A* Pro Feature:
This is an A* Pathfinding Project Pro feature only. This function/class/variable might not exist in the Free version of the A* Pathfinding Project or the functionality might be limited
The Pro version can be bought here
Stack<GraphNode> floodStack
private

Stack used for flood-filling the graph.

It is saved to minimize memory allocations.

bool fullGetNearestSearch = false

Do a full GetNearest search for all graphs.

Additional searches will normally only be done on the graph which in the first fast search seemed to have the closest node. With this setting on, additional searches will be done on all graphs since the first check is not always completely accurate.
More technically: GetNearestForce on all graphs will be called if true, otherwise only on the one graph which's GetNearest search returned the best node.
Usually faster when disabled, but higher quality searches when enabled. When using a a navmesh or recast graph, for best quality, this setting should be combined with the Pathfinding.NavMeshGraph.accurateNearestNode setting set to true.

Note
For the PointGraph this setting doesn't matter much as it has only one search mode.
System.Threading.AutoResetEvent graphUpdateAsyncEvent = new System.Threading.AutoResetEvent(false)
private
Todo:
Should be signaled in OnDestroy
float graphUpdateBatchingInterval = 0.2F

How often should graphs be updated.

If batchGraphUpdates is true, this defines the minimum number of seconds between each graph update.

This can have a positive impact on pathfinding throughput since the pathfinding threads do not need to be stopped as often, and it reduces the overhead per graph update. All graph updates are still applied however, they are just batched together so that more of them are applied at the same time.

However do not use this if you want minimal latency between a graph update being requested and it being applied. This only applies to graph updates requested using the UpdateGraphs method. Not those requested using RegisterSafeUpdate or AddWorkItem.

Queue<GraphUpdateObject> graphUpdateQueue
private

Stack containing all waiting graph update queries.

Add to this stack by using UpdateGraphs

See Also
UpdateGraphs
Queue<GUOSingle> graphUpdateQueueAsync = new Queue<GUOSingle>()
private

Queue of all async graph updates waiting to be executed.

Queue<GUOSingle> graphUpdateQueueRegular = new Queue<GUOSingle>()
private

Queue of all non-async graph updates waiting to be executed.

bool graphUpdateRoutineRunning = false
private
Thread graphUpdateThread
private

Reference to the thread which handles async graph updates.

See Also
ProcessGraphUpdatesAsync
Heuristic heuristic = Heuristic.Euclidean

The heuristic to use.

The heuristic, often referred to as 'H' is the estimated cost from a node to the target. Different heuristics affect how the path picks which one to follow from multiple possible with the same length

See Also
Pathfinding.Heuristic
float heuristicScale = 1F

The scale of the heuristic.

If a smaller value than 1 is used, the pathfinder will search more nodes (slower). If 0 is used, the pathfinding will be equal to dijkstra's algorithm. If a value larger than 1 is used the pathfinding will (usually) be faster because it expands fewer nodes, but the paths might not longer be optimal

string inGameDebugPath

Debug string from the last completed path.

Will be updated if logPathResults == PathLog.InGame

bool isEditor = true
static
bool isRegisteredForUpdate = false
private

Makes sure QueueGraphUpdates will not queue multiple graph update orders.

float lastGraphUpdate = -9999F
private

Time the last graph update was done.

Used to group together frequent graph updates to batches

float lastScanTime = 0F

The time it took for the last call to Scan() to complete.

Used to prevent automatically rescanning the graphs too often (editor only)

uint lastUniqueAreaIndex = 0

The last area index which was used.

Used for the FloodFill function to start flood filling with an unused area.

See Also
FloodFill(Node node)
PathLog logPathResults = PathLog.Normal

The amount of debugging messages.

Use less debugging to improve performance (a bit) or just to get rid of the Console spamming.
Use more debugging (heavy) if you want more information about what the pathfinding is doing.
InGame will display the latest path log using in game GUI.

bool manualDebugFloorRoof = false

If set, the debugFloor and debugRoof values will not be automatically recalculated.

Note
Only relevant in the editor
float maxFrameTime = 1F

Max number of milliseconds to spend each frame for pathfinding.

At least 500 nodes will be searched each frame (if there are that many to search). When using multithreading this value is quite irrelevant, but do not set it too low since that could add upp to some overhead, 10ms will work good for multithreading

float maxNearestNodeDistance = 100

Max Nearest Node Distance.

When searching for a nearest node, this is the limit (world units) for how far away it is allowed to be.

See Also
Pathfinding.NNConstraint.constrainDistance
int minAreaSize = 0

Defines the minimum amount of nodes in an area.

If an area has less than this amount of nodes, the area will be flood filled again with the area ID GraphNode.MaxAreaIndex-1, it shouldn't affect pathfinding in any significant way.
If you want to be able to separate areas from one another for some reason (for example to do a fast check to see if a path is at all possible) you should set this variable to 0.
Can be found in A* Inspector–>Settings–>Min Area Size

Version
Since version 3.6, this variable should in most cases be set to 0 since the max number of area indices available has been greatly increased.
ushort nextFreePathID = 1
private

The next unused Path ID.

Incremented for every call to GetFromPathPool

int nextNodeIndex = 1
private

Holds the next node index which has not been used by any previous node.

See Also
nodeIndexPool
Stack<int> nodeIndexPool = new Stack<int>()
private

Holds indices for nodes that have been destroyed.

To avoid trashing a lot of memory structures when nodes are frequently deleted and created, node indices are reused.

System.Action On65KOverflow
static

Called when pathID overflows 65536 and resets back to zero.

Note
This callback will be cleared every time it is called, so if you want to register to it repeatedly, register to it directly on receiving the callback as well.
System.Action OnAwakeSettings
static

Called on Awake before anything else is done.

This is called at the start of the Awake call, right after active has been set, but this is the only thing that has been done.
Use this when you want to set up default settings for an AstarPath component created during runtime since some settings can only be changed in Awake (such as multithreading related stuff)

//Create a new AstarPath object on Start and apply some default settings
public void Start () {
AstarPath.OnAwakeSettings += ApplySettings;
AstarPath astar = AddComponent<AstarPath>();
}
public void ApplySettings () {
//Unregister from the delegate
AstarPath.OnAwakeSettings -= ApplySettings;
//For example threadCount should not be changed after the Awake call
//so here's the only place to set it if you create the component during runtime
}
System.Action OnDrawGizmosCallback

Used internally to enable gizmos in editor scripts.

Warning
Used internally by the editor, do not use this in your code
OnGraphDelegate OnGraphPostScan
static

Called for each graph after they have been scanned.

All other graphs might not have been scanned yet.

OnGraphDelegate OnGraphPreScan
static

Called for each graph before they are scanned.

OnScanDelegate OnGraphsUpdated
static

Called when any graphs are updated.

Register to for example recalculate the path whenever a graph changes.

System.Action OnGraphsWillBeUpdated
System.Action OnGraphsWillBeUpdated2
OnScanDelegate OnLatePostScan
static

Called after scanning has completed fully.

This is called as the last thing in the Scan function.

OnPathDelegate OnPathPostSearch
static

Called for each path after searching.

Be careful when using multithreading since this will be called from a different thread.

OnPathDelegate OnPathPreSearch
static

Called for each path before searching.

Be careful when using multithreading since this will be called from a different thread.

OnScanDelegate OnPostScan
static

Called after scanning.

This is called before applying links, flood-filling the graphs and other post processing.

OnScanDelegate OnPreScan
static

Called before starting the scanning.

System.Action OnThreadSafeCallback
staticprivate

Will send a callback when it is safe to update the nodes.

Register to this with RegisterThreadSafeNodeUpdate When it is safe is defined as between the path searches. This callback will only be sent once and is nulled directly after the callback is sent.

System.Action OnUnloadGizmoMeshes

Used internally to unload temporary meshes in the editor.

Warning
Used internally by the editor, do not use this in your code
ThreadControlQueue pathQueue = new ThreadControlQueue(0)
private

Holds all paths waiting to be calculated.

Path pathReturnPop
private

A temporary queue for paths which weren't returned due to large processing time.

When some time limit is exceeded in ReturnPaths, paths are put in this queue until the next frame.

Paths contain a member called 'next', so this actually forms a linked list.

See Also
ReturnPaths
Pathfinding.Util.LockFreeStack pathReturnStack = new Pathfinding.Util.LockFreeStack()
staticprivate

Holds all paths which are waiting to be flagged as completed.

See Also
ReturnPaths
bool prioritizeGraphs = false

Prioritize graphs.

Graphs will be prioritized based on their order in the inspector. The first graph which has a node closer than prioritizeGraphsLimit will be chosen instead of searching all graphs.

float prioritizeGraphsLimit = 1F

Distance limit for prioritizeGraphs.

See Also
prioritizeGraphs
System.Threading.ManualResetEvent processingGraphUpdatesAsync = new System.Threading.ManualResetEvent(true)
private
bool processingWorkItems = false
private
bool queuedWorkItemFloodFill = false
private

True if any work items have queued a flood fill.

See Also
QueueWorkItemFloodFill
readonly System.Object safeUpdateLock = new object()
staticprivate
bool scanOnStartup = true

If true, all graphs will be scanned in Awake.

This does not include loading from the cache. If you disable this, you will have to call AstarPath.active.Scan () yourself to enable pathfinding. Alternatively you could load a saved graph from a file.

bool showGraphs = false

Shows or hides graph inspectors.

Used internally by the editor

bool showNavGraphs = true

Toggle for showing the gizmo debugging for the graphs in the scene view (editor only).

bool showSearchTree = false

If enabled, nodes will draw a line to their 'parent'.

This will show the search tree for the latest path.

Note
Only relevant in the editor
Todo:
Add a showOnlyLastPath flag to indicate whether to draw every node or only the ones visited by the latest path.
bool showUnwalkableNodes = true

Toggle to show unwalkable nodes.

Note
Only relevant in the editor
See Also
unwalkableNodeDebugSize
string [] tagNames = null
protected

Stored tag names.

See Also
AstarPath.FindTagNames
AstarPath.GetTagNames
ThreadCount threadCount = ThreadCount.None

Number of pathfinding threads to use.

Multithreading puts pathfinding in another thread, this is great for performance on 2+ core computers since the framerate will barely be affected by the pathfinding at all.

  • None indicates that the pathfinding is run in the Unity thread as a coroutine
  • Automatic will try to adjust the number of threads to the number of cores and memory on the computer. Less than 512mb of memory or a single core computer will make it revert to using no multithreading.

It is recommended that you use one of the "Auto" settings that are available. The reason is that even if your computer might be beefy and have 8 cores. Other computers might only be quad core or dual core in which case they will not benefit from more than 1 or 3 threads respectively (you usually want to leave one core for the unity thread). If you use more threads than the number of cores on the computer it is mostly just wasting memory, it will not run any faster. The extra memory usage is not trivially small. Each thread needs to keep a small amount of data for each node in all the graphs. It is not the full graph data but it is proportional to the number of nodes. The automatic settings will inspect the machine it is running on and use that to determine the number of threads so that no memory is wasted.

The exception is if you only have one (or maybe two characters) active at time. Then you should probably just go with one thread always since it is very unlikely that you will need the extra throughput given by more threads. Keep in mind that more threads primarily increases throughput by calculating different paths on different threads, it will not calculate individual paths any faster.

Note that if you are modifying the pathfinding core scripts or if you are directly modifying graph data without using any of the safe wrappers (like RegisterSafeUpdate) multithreading can cause strange errors and pathfinding stopping to work if you are not careful. For basic usage (not modding the pathfinding core) it should be safe.

Note
WebGL does not support threads at all (since javascript is single-threaded)
See Also
CalculateThreadCount
A* Pro Feature:
This is an A* Pathfinding Project Pro feature only. This function/class/variable might not exist in the Free version of the A* Pathfinding Project or the functionality might be limited
The Pro version can be bought here
IEnumerator threadEnumerator
staticprivate

When no multithreading is used, the IEnumerator is stored here.

When no multithreading is used, a coroutine is used instead. It is not directly called with StartCoroutine but a separate function has just a while loop which increments the main IEnumerator. This is done so other functions can step the thread forward at any time, without having to wait for Unity to update it.

See Also
CalculatePaths
CalculatePathsHandler
PathThreadInfo [] threadInfos = new PathThreadInfo[0]
staticprivate

Holds info about each thread.

The first item will hold information about the pathfinding coroutine when not using multithreading.

Thread [] threads
staticprivate

References to each of the pathfinding threads.

float unwalkableNodeDebugSize = 0.3F

Size of the red cubes shown in place of unwalkable nodes.

Note
Only relevant in the editor
See Also
showUnwalkableNodes
int waitForPathDepth = 0
staticprivate
Queue<AstarWorkItem> workItems = new Queue<AstarWorkItem>()
private
bool workItemsQueued = false
private

True if any work items are currently queued.

Property Documentation

PathHandler debugPathData
get

NodeRunData from debugPath.

Returns null if debugPath is null

NavGraph [] graphs
getset
System.Type [] graphTypes
get
bool IsAnyGraphUpdatesQueued
get

Returns if any graph updates are waiting to be applied.

bool isScanning
getset

Set when scanning is being done.

It will be true up until the FloodFill is done. Used to better support Graph Update Objects called for example in OnPostScan

bool IsUsingMultithreading
staticget

Returns whether or not multithreading is used.

Exceptions
System.ExceptionIs thrown when it could not be decided if multithreading was used or not. This should not happen if pathfinding is set up correctly.
Note
This uses info about if threads are running right now, it does not use info from the settings on the A* object.
bool limitGraphUpdates
getset

Batch graph updates.

Deprecated:
This field has been renamed to 'batchGraphUpdates'.
float maxGraphUpdateFreq
getset

Limit for how often should graphs be updated.

Deprecated:
This field has been renamed to 'graphUpdateBatchingInterval'.
float maxNearestNodeDistanceSqr
get

Max Nearest Node Distance Squared.

See Also
maxNearestNodeDistance
int NumParallelThreads
staticget

Number of parallel pathfinders.

Returns the number of concurrent processes which can calculate paths at once. When using multithreading, this will be the number of threads, if not using multithreading it is always 1 (since only 1 coroutine is used).

See Also
threadInfos
IsUsingMultithreading
System.Version Version
staticget

The version number for the A* Pathfinding Project.


The documentation for this class was generated from the following file: