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

Main Pathfinding System. More...

+ Inheritance diagram for AstarPath:
+ Collaboration diagram for AstarPath:

Public Types

enum  AstarDistribution { WebsiteDownload, AssetStore }
 

Public Member Functions

void ApplyLinks ()
 Applies links to the scanned graphs.
 
bool AutoScan ()
 Called by editor scripts to rescan the graphs e.g when the user moved a graph.
 
void Awake ()
 Sets up all needed variables and scans the graphs.
 
void DataUpdate ()
 Called when a major data update has been done, makes sure everything is wired up correctly.
 
void FloodFill (Node seed)
 Floodfills starting from the specified node.
 
void FloodFill (Node seed, int 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 run.
 
void FlushThreadSafeCallbacks ()
 Forces thread safe callbacks to run.
 
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, Node hint)
 Returns the nearest node to a position using the specified NNConstraint.
 
Node GetNearest (Ray ray)
 Returns the node closest to the ray (slow).
 
ushort GetNextPathID ()
 Returns the next free path ID.
 
string[] GetTagNames ()
 Returns tag names.
 
void Initialize ()
 Initializes various variables.
 
void LogPathResults (Path p)
 Prints path results to the log.
 
void LogProfiler ()
 
void NodeCountChanged ()
 Should be called whenever the total nodecount has changed for the graphs.
 
void OnApplicationQuit ()
 Terminates eventual pathfinding threads when the application quits.
 
void OnDestroy ()
 Clears up variables and other stuff, destroys graphs.
 
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 QueueGraphUpdates ()
 Will apply queued graph updates as soon as possible, regardless of limitGraphUpdates.
 
void ResetProfiler ()
 
void ReturnPaths (bool timeSlice)
 Returns all paths in the return stack.
 
IEnumerator ReturnsPathsHandler ()
 Coroutine to return thread safe path callbacks.
 
void Scan ()
 Scans all graphs.
 
IEnumerable< ProgressScanLoop ()
 Scans all graphs.
 
void SetUpReferences ()
 Makes sure active is set to this object and that astarData is not null.
 
void Update ()
 
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.
 
void UpdatePathThreadInfoNodes ()
 Updates NodeRun data in threads.
 
bool WillBlockPath (GraphUpdateObject ob, Node n1, Node n2)
 Will applying this GraphUpdateObject result in no possible path between n1 and n2.
 

Static Public 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 function.
 
static IEnumerator CalculatePathsHandler (System.Object _threadData)
 Handler for the CalculatePaths function.
 
static void CalculatePathsThreaded (System.Object _threadInfo)
 Main pathfinding function (multithreaded).
 
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 ForceCallThreadSafeCallbacks ()
 Forces thread safe callbacks to be called.
 
static bool IsPathPossible (Node n1, Node n2)
 Returns if there is a walkable path from n1 to n2.
 
static void LockThread (System.Object _astar)
 
static void RegisterSafeUpdate (OnVoidDelegate callback, bool threadSafe)
 Will send a callback when it is safe to update nodes.
 
static void StartPath (Path p)
 Puts the Path in queue for calculation.
 
static void WaitForPath (Path p)
 Wait for the specified path to be calculated.
 

Public Attributes

AstarData astarData
 Reference to the Pathfinding::AstarData object for this graph.
 
const AstarDistribution Distribution = AstarDistribution.WebsiteDownload
 Used by the editor to guide the user to the correct place to download updates.
 
Stack< NodefloodStack
 Stack used for flood-filling the graph.
 
Queue< GraphUpdateObjectgraphUpdateQueue
 Stack containing all waiting graph update queries.
 
bool isScanning = false
 Set when scanning is being done.
 
int lastUniqueAreaIndex = 0
 The last area index which was used.
 
bool showGraphs = false
 Shows or hides graph inspectors.
 

Static Public Attributes

static new AstarPath active
 Returns the active AstarPath object in the scene.
 
static readonly bool HasPro = true
 Used by the editor to show some Pro specific stuff.
 
static Stack< PathPathPool
 Stack to hold paths waiting to be recycled.
 
static Queue< PathpathQueue = new Queue<Path> ()
 
static
Pathfinding.Util.LockFreeStack 
pathReturnStack = new Pathfinding.Util.LockFreeStack()
 
static IEnumerator threadEnumerator
 When no multithreading is used, the IEnumerator is stored here.
 
static PathThreadInfo[] threadInfos
 Holds info about each thread.
 
static Thread[] threads
 

Properties

static int ActiveThreadsCount [get]
 Number of threads currently active.
 
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.
 
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 Member Functions

IEnumerator DelayedGraphUpdate ()
 Waits a moment with updating graphs.
 
void DoUpdateGraphs ()
 Updates the graphs based on the graphUpdateQueue.
 
IEnumerator UpdateGraphsInteral (GraphUpdateObject ob, float t)
 Update all graphs using the GraphUpdateObject after t seconds.
 

Static Private Member Functions

static void ResetQueueStates ()
 Resets all event flags.
 
static void TrickAbortThreads ()
 This will trick threads to think there is more work to be done and then abort them gracefully.
 
static void TryCallThreadSafeCallbacks ()
 

Private Attributes

bool acceptNewPaths = true
 Disables or enables new paths to be added to the queue.
 
bool graphUpdateRoutineRunning = false
 
bool isRegisteredForUpdate = false
 
bool isUpdatingGraphs = false
 
float lastGraphUpdate = -9999F
 Time the last graph update was done.
 
ushort nextFreePathID = 1
 The next unused Path ID.
 
Path pathReturnPop
 A temporary queue for paths which weren't returned due to large processing time.
 

Static Private Attributes

static bool doSetQueueState = true
 
static int numActiveThreads = 0
 Number of threads currently working.
 
static readonly ManualResetEvent pathQueueFlag = new ManualResetEvent (false)
 Flag set if there are paths to calculate.
 
static readonly ManualResetEvent safeUpdateFlag = new ManualResetEvent (false)
 Thread flag, set if safe or thread safe updates need to be done.
 
static readonly System.Object safeUpdateLock = new object()
 
static readonly ManualResetEvent threadSafeUpdateFlag = new ManualResetEvent (false)
 Thread flag, reset while a thread wait for the Unity thread to call threadsafe updates.
 
static bool threadSafeUpdateState = false
 
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 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.
 
bool stepByStep = true
 If enabled, only one node will be searched per search iteration (frame).
 
PathLog logPathResults = PathLog.Normal
 The amount of debugging messages.
 

Inspector - Settings

float maxNearestNodeDistanceSqr [get]
 Max Nearest Node Distance Squared.
 
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.
 
const int InitialBinaryHeapSize = 512
 The initial max size of the binary heap.
 
bool recyclePaths = false
 Recycle paths to reduce memory allocations.
 
int minAreaSize = 10
 Defines the minimum amount of nodes in an area.
 
bool limitGraphUpdates = true
 Limit graph updates.
 
float maxGraphUpdateFreq = 0.2F
 How often should graphs be updated.
 
string[] tagNames = null
 Stored tag names.
 

Debug Members

NodeRunData 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
 This is the debug string from the last completed path.
 
static int PathsCompleted = 0
 How many paths has been computed this run.
 
static System.Int64 TotalSearchedNodes = 0
 
static System.Int64 TotalSearchTime = 0
 

Callbacks

OnVoidDelegate OnDrawGizmosCallback
 Used to enable gizmos in editor scripts.
 
OnVoidDelegate OnGraphsWillBeUpdated
 
OnVoidDelegate OnGraphsWillBeUpdated2
 
static OnVoidDelegate 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 OnVoidDelegate On65KOverflow
 Called when pathID overflows 65536.
 
static OnVoidDelegate OnSafeCallback
 Will send a callback when it is safe to update the nodes.
 
static OnVoidDelegate OnThreadSafeCallback
 Will send a callback when it is safe to update the nodes.
 

Detailed Description

Main Pathfinding System.

This class handles all the pathfinding system, calculates all paths and stores the info.
This class is a singleton class, meaning it 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, and MultiTargetFree.cs.

Member Function Documentation

void ApplyLinks ( )

Applies links to the scanned graphs.

Called right after OnPostScan and before FloodFill().

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Awake ( )

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

+ Here is the call graph for this function:

static IEnumerator CalculatePaths ( System.Object  _threadInfo)
static

Main pathfinding function.

This function will calculate the paths in the pathfinding queue

See Also
CalculatePaths

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

static IEnumerator CalculatePathsHandler ( System.Object  _threadData)
static

Handler for the CalculatePaths function.

Will initialize an IEnumerator from the CalculatePaths function. This function has a loop which will increment the CalculatePaths function state by one every time. Supposed to be called using StartCoroutine, this enabled other functions to also increment the state of the function when needed using the threadEnumerator variable.

See Also
CalculatePaths
threadEnumerator

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

static void CalculatePathsThreaded ( System.Object  _threadInfo)
static

Main pathfinding function (multithreaded).

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

See Also
CalculatePaths
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

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

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.

+ Here is the caller graph for this function:

void DataUpdate ( )

Called when a major data update has been done, makes sure everything is wired up correctly.

For example when updating number of graphs, rescanning graphs, adding or removing nodes are considered major changes. Should not be called during or before Awake has been called on the AstarPath object.

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

IEnumerator DelayedGraphUpdate ( )
private

Waits a moment with updating graphs.

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

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void DoUpdateGraphs ( )
private

Updates the graphs based on the graphUpdateQueue.

See Also
UpdateGraphs

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

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

+ Here is the call graph for this function:

void FloodFill ( )

Floodfills all graphs and updates areas for every node.

See Also
Pathfinding::Node::area

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void FlushGraphUpdates ( )

Forces graph updates to run.

This will force all graph updates to run immidiately. Or rather, it will block the Unity main thread until graph updates can be performed 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, 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 FlushThreadSafeCallbacks, 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 thread safe callbacks. 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).

Examples:
MovePointNode.cs.

+ Here is the call graph for this function:

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 appropriate name.

+ Here is the caller graph for this function:

static void ForceCallThreadSafeCallbacks ( )
static

Forces thread safe callbacks to be called.

This method should only be called from inside another thread safe callback to for example instantly run some graph updates.

Exceptions
System.InvalidOperationExceptionif any threads are detected to be active and running

+ Here is the caller graph for this function:

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
Examples:
MovePointNode.cs.

+ Here is the caller graph for this function:

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

+ Here is the call graph for this function:

NNInfo GetNearest ( Vector3  position,
NNConstraint  constraint,
Node  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

+ Here is the call graph for this function:

Node GetNearest ( Ray  ray)

Returns the node closest to the ray (slow).

Warning
This function is brute-force and very slow, it can barely be used once per frame
ushort GetNextPathID ( )

Returns the next free path ID.

If the next free path ID overflows 65535, a cleanup operation is queued

See Also
Pathfinding::CleanupPath65K

+ Here is the caller graph for this function:

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

+ Here is the caller graph for this function:

void Initialize ( )

Initializes various variables.

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

See Also
AstarData.FindGraphTypes
SetUpReferences

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

static bool IsPathPossible ( Node  n1,
Node  n2 
)
static

Returns if there is a walkable path from n1 to n2.

If you are making changes to the graph, areas must first be recaculated using FloodFill()

Note
This might return true for small areas even if there is no possible path if minAreaSize is greater than zero (0). So when using this, it is recommended to set minAreaSize to 0.
Only valid as long as both nodes are walkable.
See Also
GetNearest
Deprecated:
Use Pathfinding.GraphUpdateUtilities.IsPathPossible instead
void LogPathResults ( Path  p)

Prints path results to the log.

What it prints can be controled using logPathResults.

See Also
logPathResults
PathLog
Pathfinding::Path::DebugString

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void NodeCountChanged ( )

Should be called whenever the total nodecount has changed for the graphs.

Recreates temporary node data for every thread

+ Here is the call graph for this function:

void OnDestroy ( )

Clears up variables and other stuff, destroys graphs.

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

+ Here is the call graph for this function:

void OnGUI ( )

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

See Also
logPathResults PathLog
void QueueGraphUpdates ( )

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

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

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

static void RegisterSafeUpdate ( OnVoidDelegate  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).

Warning
Note that if you do not set threadSafe to true, the callback might not be called from the Unity thread, DO NOT call any part of the Unity API from those callbacks except for Debug.Log
Node node = AstarPath.active.GetNearest (transform.position).node;
node.walkable = false;
}, false);
Node node = AstarPath.active.GetNearest (transform.position).node;
node.position = (Int3)transform.position;
}, true);

Note that the second example uses transform in the callback, and must thus be threadSafe.

Examples:
MovePointNode.cs.

+ Here is the caller graph for this function:

static void ResetQueueStates ( )
staticprivate

Resets all event flags.

This should be called when resetting the static members of AstarPath.

See Also
OnDestroy

+ Here is the caller graph for this function:

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.

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

IEnumerator ReturnsPathsHandler ( )

Coroutine to return thread safe path callbacks.

This method will infinitely loop and call ReturnPaths

See Also
ReturnPaths

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

IEnumerable<Progress> ScanLoop ( )

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

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void SetUpReferences ( )

Makes 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

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

static void TrickAbortThreads ( )
staticprivate

This will trick threads to think there is more work to be done and then abort them gracefully.

When they think there is more work to be done, they will first test if new paths should be accepted, now they are not, so the threads will abort gracefully. Only call this when you want to abort all threads. For example in the OnDestroy function. After this function has been called, it's good to loop through all threads and Thread.Join them with some timeout. If the timeout exceeds, you can call Thread.Abort on them

See Also
OnDestroy
acceptNewPaths

+ Here is the caller graph for this function:

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.

See Also
Update
DoUpdateGraphs
Examples:
MovePointNode.cs.

+ Here is the caller graph for this function:

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.

+ Here is the call graph for this function:

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

+ Here is the call graph for this function:

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 limitGraphUpdates)

See Also
FlushGraphUpdates

+ Here is the call graph for this function:

void UpdatePathThreadInfoNodes ( )

Updates NodeRun data in threads.

Called by AstarData::CreateNodeRuns

If the ASTAR_SINGLE_THREAD_OPTIMIZE define is enabled this function will only do some simple error checking.

See Also
AstarData::CreateNodeRuns

+ Here is the caller graph for this function:

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.

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 ocurr 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.

+ Here is the call graph for this function:

bool WillBlockPath ( GraphUpdateObject  ob,
Node  n1,
Node  n2 
)

Will applying this GraphUpdateObject result in no possible path between n1 and n2.

Use this only with basic GraphUpdateObjects since it needs special backup logic, it probably wont work with your own specialized ones. This function is quite a lot slower than a standart Graph Update, but not so much it will slow the game down.

Note
This might return false for small areas even if it would block the path if minAreaSize is greater than zero (0). So when using this, it is recommended to set minAreaSize to 0.
See Also
AstarPath::GetNearest
Deprecated:
Use Pathfinding.GraphUpdateUtilities.UpdateGraphsNoBlock instead

+ Here is the call graph for this function:

Member Data Documentation

bool acceptNewPaths = true
private

Disables or enables new paths to be added to the queue.

Setting this to false also makes the pathfinding thread (if using multithreading) to abort as soon as possible. It is used when OnDestroy is called to abort the pathfinding thread.

new AstarPath active
static

Returns the active AstarPath object in the scene.

Examples:
MovePointNode.cs.
AstarData astarData

Reference to the Pathfinding::AstarData object for this graph.

The AstarData object stores information about all graphs.

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.

See Also
debugRoof
GraphDebugMode debugMode

The mode to use for drawing nodes in the sceneview.

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.

See Also
debugFloor
Stack<Node> floodStack

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.

Additinal searches will normally only be done on the graph which in the first, fast searches proved to have the closest node. With this setting on, additional searches will be done on all graphs.
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.
Queue<GraphUpdateObject> graphUpdateQueue

Stack containing all waiting graph update queries.

Add to this stack by using UpdateGraphs

See Also
UpdateGraphs
readonly bool HasPro = true
static

Used by the editor to show some Pro specific stuff.

Note that setting this to true will not grant you any additional features

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

This is the debug string from the last completed path.

Will be updated if logPathResults == PathLog.InGame

const int InitialBinaryHeapSize = 512

The initial max size of the binary heap.

The binary heaps will be expanded if necessary.

bool isScanning = false

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

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)

int 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)
bool limitGraphUpdates = true

Limit graph updates.

If toggled, graph updates will be executed less often (specified by maxGraphUpdateFreq).

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.

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 maxGraphUpdateFreq = 0.2F

How often should graphs be updated.

If limitGraphUpdates is true, this defines the minimum amount of seconds between each graph update.

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 = 10

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 254, 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

ushort nextFreePathID = 1
private

The next unused Path ID.

Incremented for every call to GetFromPathPool

int numActiveThreads = 0
staticprivate

Number of threads currently working.

Threads are sleeping when there is no work to be done or there is a work block (such as when updating graphs)

OnVoidDelegate On65KOverflow
static

Called when pathID overflows 65536.

The Pathfinding::CleanupPath65K will be added to the queue, and directly after, this callback will be called.

Note
This callback will be cleared every timed it is called, so if you want to register to it repeatedly, register to it directly on receiving the callback as well.
OnVoidDelegate 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 useMultithreading should not be changed after the Awake call
//so here's the only place to set it if you create the component during runtime
AstarPath.active.useMultithreading = true;
}
OnVoidDelegate OnDrawGizmosCallback

Used to enable gizmos in editor scripts.

Used internally by the editor, do not use this in game code

OnGraphDelegate OnGraphPostScan
static

Called for each graph after they have been scanned.

All other graphs might not have been scanned yet.

OnScanDelegate OnGraphsUpdated
static

Called when any graphs are updated.

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

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 carefull when using multithreading since this will be called from a different thread.

OnPathDelegate OnPathPreSearch
static

Called for each path before searching.

Be carefull 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.

OnVoidDelegate OnSafeCallback
staticprivate

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

Register to this with RegisterSafeNodeUpdate 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.

Warning
Note that these callbacks are not thread safe when using multithreading, DO NOT call any part of the Unity API from these callbacks except for Debug.Log
OnVoidDelegate 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.

See Also
OnSafeCallback
Queue<Path> pathQueue = new Queue<Path> ()
static
Todo:
Check scene switches
readonly ManualResetEvent pathQueueFlag = new ManualResetEvent (false)
staticprivate

Flag set if there are paths to calculate.

Might get reset if a function wants to pause pathfinding (for example to update graphs)Thread flag, reset if there are no more paths in the queue

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 on this queue until the next frame.

int PathsCompleted = 0
static

How many paths has been computed this run.

From application start.
Debugging variable

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
bool recyclePaths = false

Recycle paths to reduce memory allocations.

This will put paths in a pool to be reused over and over again. If you use this, your scripts using tht paths should copy the vectorPath array and node array (if used) because when the path is recycled, those arrays will be replaced. I.e you should not get data from it using myPath.someVariable (except when you get the path callback) because 'someVariable' might be changed when the path is recycled.

Note
This feature is currently disabled because it didn't lead to much better memory management, but could seriously screw up stuff if the user was not careful.
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. This is editor only.

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.

See Also
unwalkableNodeDebugSize
bool stepByStep = true

If enabled, only one node will be searched per search iteration (frame).

Used for debugging

Note
Might not apply for all path types
Deprecated:
Probably does not work for ANY path types
string [] tagNames = null
protected
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. But this can cause strange errors and pathfinding stopping to work if you are not carefull (that is, if you are modifying the pathfinding scripts). For basic usage (not modding the pathfinding core) it should be safe.

  • 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
    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
static

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
static

Holds info about each thread.

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

float unwalkableNodeDebugSize = 0.3F

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

See Also
showUnwalkableNodes

Property Documentation

int ActiveThreadsCount
staticget

Number of threads currently active.

This includes the pathfinding coroutine used for non-multithreading mode.

NodeRunData debugPathData
get

NodeRunData from debugPath.

Returns null if debugPath is null

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.
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

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