A* Pathfinding Project  4.1.8
The A* Pathfinding Project for Unity 3D
Path Class Referenceabstract

Base class for all path types. More...

Detailed Description

Base class for all path types.

Public Member Functions

void BlockUntilCalculated ()
 Blocks until this path has been calculated and returned. More...
 
void Claim (System.Object o)
 Claim this path (pooling). More...
 
void Error ()
 Aborts the path because of an error. More...
 
PathState GetState ()
 Returns the state of the path in the pathfinding pipeline. More...
 
float GetTotalLength ()
 Total Length of the path. More...
 
bool IsDone ()
 Returns if this path is done calculating. More...
 
void Release (System.Object o, bool silent=false)
 Releases a path claim (pooling). More...
 
IEnumerator WaitForPath ()
 Waits until this path has been calculated and returned. More...
 

Public Attributes

OnPathDelegate callback
 Callback to call when the path is complete. More...
 
int enabledTags = -1
 Which graph tags are traversable. More...
 
Heuristic heuristic
 Determines which heuristic to use. More...
 
float heuristicScale = 1F
 Scale of the heuristic values. More...
 
OnPathDelegate immediateCallback
 Immediate callback to call when the path is complete. More...
 
NNConstraint nnConstraint = PathNNConstraint.Default
 Constraint for how to search for nodes. More...
 
List< GraphNodepath
 Holds the path as a Node array. More...
 
ITraversalProvider traversalProvider
 Provides additional traversal information to a path request. More...
 
List< Vector3 > vectorPath
 Holds the (possibly post processed) path as a Vector3 list. More...
 

Protected Member Functions

abstract void CalculateStep (long targetTick)
 Calculates the until it is complete or the time has progressed past targetTick. More...
 
virtual void Cleanup ()
 Always called after the path has been calculated. More...
 
void DebugStringPrefix (PathLog logMode, System.Text.StringBuilder text)
 Writes text shared for all overrides of DebugString to the string builder. More...
 
void DebugStringSuffix (PathLog logMode, System.Text.StringBuilder text)
 Writes text shared for all overrides of DebugString to the string builder. More...
 
abstract void Initialize ()
 Initializes the path. More...
 
virtual void OnEnterPool ()
 Called when the path enters the pool. More...
 
abstract void Prepare ()
 Called before the path is started. More...
 
void PrepareBase (PathHandler pathHandler)
 Prepares low level path variables for calculation. More...
 
virtual void Reset ()
 Reset all values to their default values. More...
 
virtual void ReturnPath ()
 Calls callback to return the calculated path. More...
 
virtual void Trace (PathNode from)
 Traces the calculated path from the end node to the start. More...
 

Protected Attributes

PathCompleteState completeState
 Backing field for CompleteState. More...
 
PathNode currentR
 The node currently being processed. More...
 
bool hasBeenReset
 True if the Reset function has been called. More...
 
Int3 hTarget
 Target to use for H score calculations. More...
 
GraphNode hTargetNode
 Target to use for H score calculation. More...
 
int [] internalTagPenalties
 The tag penalties that are actually used. More...
 
int [] manualTagPenalties
 Tag penalties set by other scripts. More...
 
PathHandler pathHandler
 Data for the thread calculating this path. More...
 

Package Functions

uint CalculateHScore (GraphNode node)
 Estimated cost from the specified node to the target. More...
 
bool CanTraverse (GraphNode node)
 Returns if the node can be traversed. More...
 
virtual string DebugString (PathLog logMode)
 Returns a string with information about it. More...
 
void FailWithError (string msg)
 Causes the path to fail and sets errorLog to msg. More...
 
virtual uint GetConnectionSpecialCost (GraphNode a, GraphNode b, uint currentCost)
 May be called by graph nodes to get a special cost for some connections. More...
 
Int3 GetHTarget ()
 
uint GetTagPenalty (int tag)
 Returns penalty for the given tag. More...
 
uint GetTraversalCost (GraphNode node)
 
void Log (string msg)
 Appends a message to the errorLog. More...
 
void LogError (string msg)
 Logs an error. More...
 
void ReleaseSilent (System.Object o)
 Releases the path silently (pooling). More...
 

Package Attributes

float duration
 How long it took to calculate this path in milliseconds. More...
 
Path next
 Internal linked list implementation. More...
 
int searchedNodes
 Number of nodes this path has searched. More...
 

Properties

PathCompleteState CompleteState [get, protected set]
 Current state of the path. More...
 
bool error [get]
 If the path failed, this is true. More...
 
string errorLog [get, private set]
 Additional info on why a path failed. More...
 
virtual bool FloodingPath [get]
 True for paths that want to search all nodes and not jump over nodes as optimizations. More...
 
PathHandler IPathInternals. PathHandler [get]
 
ushort pathID [get, private set]
 ID of this path. More...
 
PathState PipelineState [get, private set]
 Returns the state of the path in the pathfinding pipeline. More...
 
bool IPathInternals. Pooled [get, set]
 True if the path is currently pooled. More...
 
bool recycled [get]
 True if the path is currently recycled (i.e in the path pool). More...
 
int [] tagPenalties [get, set]
 Penalties for each tag. More...
 
- Properties inherited from IPathInternals
PathHandler PathHandler [get]
 
bool Pooled [get, set]
 

Private Member Functions

void IPathInternals. AdvanceState (PathState s)
 Threadsafe increment of the state. More...
 
void IPathInternals. CalculateStep (long targetTick)
 
void IPathInternals. Cleanup ()
 
void ErrorCheck ()
 Performs some error checking. More...
 
void IPathInternals. Initialize ()
 
void IPathInternals. OnEnterPool ()
 
void IPathInternals. Prepare ()
 
void IPathInternals. PrepareBase (PathHandler handler)
 
void IPathInternals. Reset ()
 
void IPathInternals. ReturnPath ()
 

Private Attributes

List< System.Object > claimed = new List<System.Object>()
 List of claims on this path with reference objects. More...
 
bool releasedNotSilent
 True if the path has been released with a non-silent call yet. More...
 
System.Object stateLock = new object ()
 

Static Private Attributes

static readonly int [] ZeroTagPenalties = new int[32]
 List of zeroes to use as default tag penalties. More...
 

Member Function Documentation

◆ AdvanceState()

void IPathInternals. AdvanceState ( PathState  s)
private

Threadsafe increment of the state.

Implements IPathInternals.

◆ BlockUntilCalculated()

void BlockUntilCalculated ( )

Blocks until this path has been calculated and returned.

Normally it takes a few frames for a path to be 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.

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.
Path p = seeker.StartPath (transform.position, transform.position + Vector3.forward * 10);
p.BlockUntilCalculated();
// The path is calculated now
See also
This is equivalent to calling AstarPath.BlockUntilCalculated(Path)
WaitForPath

◆ CalculateHScore()

uint CalculateHScore ( GraphNode  node)
package

Estimated cost from the specified node to the target.

See also
https://en.wikipedia.org/wiki/A*_search_algorithm

◆ CalculateStep() [1/2]

abstract void CalculateStep ( long  targetTick)
protectedpure virtual

Calculates the until it is complete or the time has progressed past targetTick.

Implements IPathInternals.

Implemented in MultiTargetPath, ABPath, RandomPath, FloodPath, ConstantPath, FloodPathTracer, and XPath.

◆ CalculateStep() [2/2]

void IPathInternals. CalculateStep ( long  targetTick)
private

Implements IPathInternals.

◆ CanTraverse()

bool CanTraverse ( GraphNode  node)
package

Returns if the node can be traversed.

This per default equals to if the node is walkable and if the node's tag is included in enabledTags

◆ Claim()

void Claim ( System.Object  o)

Claim this path (pooling).

A claim on a path will ensure that it is not pooled. If you are using a path, you will want to claim it when you first get it and then release it when you will not use it anymore. When there are no claims on the path, it will be reset and put in a pool.

This is essentially just reference counting.

The object passed to this method is merely used as a way to more easily detect when pooling is not done correctly. It can be any object, when used from a movement script you can just pass "this". This class will throw an exception if you try to call Claim on the same path twice with the same object (which is usually not what you want) or if you try to call Release with an object that has not been used in a Claim call for that path. The object passed to the Claim method needs to be the same as the one you pass to this method.

See also
Release
Pool
Pooling
https://en.wikipedia.org/wiki/Reference_counting

◆ Cleanup() [1/2]

virtual void Cleanup ( )
protectedvirtual

Always called after the path has been calculated.

Guaranteed to be called before other paths have been calculated on the same thread. Use for cleaning up things like node tagging and similar.

Implements IPathInternals.

Reimplemented in MultiTargetPath, ABPath, and ConstantPath.

◆ Cleanup() [2/2]

void IPathInternals. Cleanup ( )
private

Implements IPathInternals.

◆ DebugString()

virtual string DebugString ( PathLog  logMode)
packagevirtual

Returns a string with information about it.

More information is emitted when logMode == Heavy. An empty string is returned if logMode == None or logMode == OnlyErrors and this path did not fail.

Reimplemented in MultiTargetPath, and ABPath.

◆ DebugStringPrefix()

void DebugStringPrefix ( PathLog  logMode,
System.Text.StringBuilder  text 
)
protected

Writes text shared for all overrides of DebugString to the string builder.

See also
DebugString

◆ DebugStringSuffix()

void DebugStringSuffix ( PathLog  logMode,
System.Text.StringBuilder  text 
)
protected

Writes text shared for all overrides of DebugString to the string builder.

See also
DebugString

◆ Error()

void Error ( )

Aborts the path because of an error.

Sets error to true. This function is called when an error has occurred (e.g a valid path could not be found).

See also
FailWithError

◆ ErrorCheck()

void ErrorCheck ( )
private

Performs some error checking.

Makes sure the user isn't using old code paths and that no major errors have been made.

Causes the path to fail if any errors are found.

◆ FailWithError()

void FailWithError ( string  msg)
package

Causes the path to fail and sets errorLog to msg.

◆ GetConnectionSpecialCost()

virtual uint GetConnectionSpecialCost ( GraphNode  a,
GraphNode  b,
uint  currentCost 
)
packagevirtual

May be called by graph nodes to get a special cost for some connections.

Nodes may call it when PathNode.flag2 is set to true, for example mesh nodes, which have a very large area can be marked on the start and end nodes, this method will be called to get the actual cost for moving from the start position to its neighbours instead of as would otherwise be the case, from the start node's position to its neighbours. The position of a node and the actual start point on the node can vary quite a lot.

The default behaviour of this method is to return the previous cost of the connection, essentiall making no change at all.

This method should return the same regardless of the order of a and b. That is f(a,b) == f(b,a) should hold.

Parameters
aMoving from this node
bMoving to this node
currentCostThe cost of moving between the nodes. Return this value if there is no meaningful special cost to return.

Reimplemented in ABPath.

◆ GetHTarget()

Int3 GetHTarget ( )
package

◆ GetState()

PathState GetState ( )

Returns the state of the path in the pathfinding pipeline.

Deprecated:
Use the Pathfinding.Path.PipelineState property instead

◆ GetTagPenalty()

uint GetTagPenalty ( int  tag)
package

Returns penalty for the given tag.

Parameters
tagA value between 0 (inclusive) and 32 (exclusive).

◆ GetTotalLength()

float GetTotalLength ( )

Total Length of the path.

Calculates the total length of the vectorPath. Cache this rather than call this function every time since it will calculate the length every time, not just return a cached value.

Returns
Total length of vectorPath, if vectorPath is null positive infinity is returned.

◆ GetTraversalCost()

uint GetTraversalCost ( GraphNode  node)
package

◆ Initialize() [1/2]

abstract void Initialize ( )
protectedpure virtual

Initializes the path.

Sets up the open list and adds the first node to it

Implements IPathInternals.

Implemented in MultiTargetPath, ABPath, RandomPath, FloodPath, ConstantPath, and FloodPathTracer.

◆ Initialize() [2/2]

void IPathInternals. Initialize ( )
private

Implements IPathInternals.

◆ IsDone()

bool IsDone ( )

Returns if this path is done calculating.

Returns
If CompleteState is not NotCalculated.
Note
The callback for the path might not have been called yet.
Since
Added in 3.0.8
See also
#Seeker.IsDone which also takes into account if the path callback has been called and had Modifiers applied.

◆ Log()

void Log ( string  msg)
package

Appends a message to the errorLog.

Nothing is logged to the console.

Note
If AstarPath.logPathResults is PathLog.None and this is a standalone player, nothing will be logged as an optimization.
Deprecated:
Use FailWithError instead

◆ LogError()

void LogError ( string  msg)
package

Logs an error.

Deprecated:
Use FailWithError instead

◆ OnEnterPool() [1/2]

virtual void OnEnterPool ( )
protectedvirtual

Called when the path enters the pool.

This method should release e.g pooled lists and other pooled resources The base version of this method releases vectorPath and path lists. Reset() will be called after this function, not before.

Warning
Do not call this function manually.

Implements IPathInternals.

Reimplemented in MultiTargetPath, and ConstantPath.

◆ OnEnterPool() [2/2]

void IPathInternals. OnEnterPool ( )
private

Implements IPathInternals.

◆ Prepare() [1/2]

abstract void Prepare ( )
protectedpure virtual

Called before the path is started.

Called right before Initialize

Implements IPathInternals.

Implemented in ABPath, MultiTargetPath, RandomPath, FloodPath, and ConstantPath.

◆ Prepare() [2/2]

void IPathInternals. Prepare ( )
private

Implements IPathInternals.

◆ PrepareBase() [1/2]

void PrepareBase ( PathHandler  pathHandler)
protected

Prepares low level path variables for calculation.

Called before a path search will take place. Always called before the Prepare, Initialize and CalculateStep functions

Implements IPathInternals.

◆ PrepareBase() [2/2]

void IPathInternals. PrepareBase ( PathHandler  handler)
private

Implements IPathInternals.

◆ Release()

void Release ( System.Object  o,
bool  silent = false 
)

Releases a path claim (pooling).

Removes the claim of the path by the specified object. When the claim count reaches zero, the path will be pooled, all variables will be cleared and the path will be put in a pool to be used again. This is great for performance since fewer allocations are made.

If the silent parameter is true, this method will remove the claim by the specified object but the path will not be pooled if the claim count reches zero unless a Release call (not silent) has been made earlier. This is used by the internal pathfinding components such as Seeker and AstarPath so that they will not cause paths to be pooled. This enables users to skip the claim/release calls if they want without the path being pooled by the Seeker or AstarPath and thus causing strange bugs.

See also
Claim
PathPool

◆ ReleaseSilent()

void ReleaseSilent ( System.Object  o)
package

Releases the path silently (pooling).

Deprecated:
Use Release(o, true) instead

◆ Reset() [1/2]

virtual void Reset ( )
protectedvirtual

Reset all values to their default values.

Note
All inheriting path types (e.g ConstantPath, RandomPath, etc.) which declare their own variables need to override this function, resetting ALL their variables to enable pooling of paths. If this is not done, trying to use that path type for pooling could result in weird behaviour. The best way is to reset to default values the variables declared in the extended path type and then call the base function in inheriting types with base.Reset().

Implements IPathInternals.

Reimplemented in ABPath, MultiTargetPath, FloodPath, ConstantPath, RandomPath, FloodPathTracer, and XPath.

◆ Reset() [2/2]

void IPathInternals. Reset ( )
private

Implements IPathInternals.

◆ ReturnPath() [1/2]

virtual void ReturnPath ( )
protectedvirtual

Calls callback to return the calculated path.

See also
callback

Implements IPathInternals.

Reimplemented in MultiTargetPath, and RandomPath.

◆ ReturnPath() [2/2]

void IPathInternals. ReturnPath ( )
private

Implements IPathInternals.

◆ Trace()

virtual void Trace ( PathNode  from)
protectedvirtual

Traces the calculated path from the end node to the start.

This will build an array (path) of the nodes this path will pass through and also set the vectorPath array to the path arrays positions. Assumes the vectorPath and path are empty and not null (which will be the case for a correctly initialized path).

Reimplemented in MultiTargetPath.

◆ WaitForPath()

IEnumerator WaitForPath ( )

Waits until this path has been calculated and returned.

Allows for very easy scripting.

IEnumerator Start () {
var path = seeker.StartPath(transform.position, transform.position + transform.forward*10, null);
yield return StartCoroutine(path.WaitForPath());
// The path is calculated now
}
Note
Do not confuse this with AstarPath.WaitForPath. This one will wait using yield until it has been calculated while AstarPath.WaitForPath will halt all operations until the path has been calculated.
Exceptions
System.InvalidOperationExceptionif the path is not started. Send the path to Seeker.StartPath or AstarPath.StartPath before calling this function.
See also
BlockUntilCalculated
https://docs.unity3d.com/Manual/Coroutines.html

Member Data Documentation

◆ callback

OnPathDelegate callback

Callback to call when the path is complete.

This is usually sent to the Seeker component which post processes the path and then calls a callback to the script which requested the path

◆ claimed

List<System.Object> claimed = new List<System.Object>()
private

List of claims on this path with reference objects.

◆ completeState

PathCompleteState completeState
protected

Backing field for CompleteState.

◆ currentR

PathNode currentR
protected

The node currently being processed.

◆ duration

float duration
package

How long it took to calculate this path in milliseconds.

◆ enabledTags

int enabledTags = -1

Which graph tags are traversable.

This is a bitmask so -1 = all bits set = all tags traversable. For example, to set bit 5 to true, you would do

myPath.enabledTags |= 1 << 5;

To set it to false, you would do

myPath.enabledTags &= ~(1 << 5);

The Seeker has a popup field where you can set which tags to use.

Note
If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath. So you need to change the Seeker value via script, not set this value if you want to change it via script.
See also
CanTraverse

◆ hasBeenReset

bool hasBeenReset
protected

True if the Reset function has been called.

Used to alert users when they are doing something wrong.

◆ heuristic

Heuristic heuristic

Determines which heuristic to use.

◆ heuristicScale

float heuristicScale = 1F

Scale of the heuristic values.

See also
AstarPath.heuristicScale

◆ hTarget

Int3 hTarget
protected

Target to use for H score calculations.

See also
Pathfinding.Node.H

◆ hTargetNode

GraphNode hTargetNode
protected

Target to use for H score calculation.

Used alongside hTarget.

◆ immediateCallback

OnPathDelegate immediateCallback

Immediate callback to call when the path is complete.

Warning
This may be called from a separate thread. Usually you do not want to use this one.
See also
callback

◆ internalTagPenalties

int [] internalTagPenalties
protected

The tag penalties that are actually used.

If manualTagPenalties is null, this will be ZeroTagPenalties

See also
tagPenalties

◆ manualTagPenalties

int [] manualTagPenalties
protected

Tag penalties set by other scripts.

See also
tagPenalties

◆ next

Path next
package

Internal linked list implementation.

Warning
This is used internally by the system. You should never change this.

◆ nnConstraint

Constraint for how to search for nodes.

◆ path

List<GraphNode> path

Holds the path as a Node array.

All nodes the path traverses. This may not be the same nodes as the post processed path traverses.

◆ pathHandler

PathHandler pathHandler
protected

Data for the thread calculating this path.

◆ releasedNotSilent

bool releasedNotSilent
private

True if the path has been released with a non-silent call yet.

See also
Release
Claim

◆ searchedNodes

int searchedNodes
package

Number of nodes this path has searched.

◆ stateLock

System.Object stateLock = new object ()
private

◆ traversalProvider

ITraversalProvider traversalProvider

Provides additional traversal information to a path request.

See also
Utilities for turn-based games

◆ vectorPath

List<Vector3> vectorPath

Holds the (possibly post processed) path as a Vector3 list.

◆ ZeroTagPenalties

readonly int [] ZeroTagPenalties = new int[32]
staticprivate

List of zeroes to use as default tag penalties.

Property Documentation

◆ CompleteState

PathCompleteState CompleteState
getprotected set

Current state of the path.

◆ error

bool error
get

If the path failed, this is true.

See also
errorLog
This is equivalent to checking path.CompleteState == PathCompleteState.Error

◆ errorLog

string errorLog
getprivate set

Additional info on why a path failed.

See also
AstarPath.logPathResults

◆ FloodingPath

virtual bool FloodingPath
getpackage

True for paths that want to search all nodes and not jump over nodes as optimizations.

This disables Jump Point Search when that is enabled to prevent e.g ConstantPath and FloodPath to become completely useless.

◆ PathHandler

PathHandler IPathInternals. PathHandler
getprivate

◆ pathID

ushort pathID
getprivate setpackage

ID of this path.

Used to distinguish between different paths

◆ PipelineState

PathState PipelineState
getprivate setpackage

Returns the state of the path in the pathfinding pipeline.

◆ Pooled

bool IPathInternals. Pooled
getsetprivate

True if the path is currently pooled.

Do not set this value. Only read. It is used internally.

See also
PathPool
Version
Was named 'recycled' in 3.7.5 and earlier.

◆ recycled

bool recycled
getpackage

True if the path is currently recycled (i.e in the path pool).

Do not set this value. Only read. It is used internally.

Deprecated:
Has been renamed to 'pooled' to use more widely underestood terminology

◆ tagPenalties

int [] tagPenalties
getset

Penalties for each tag.

Tag 0 which is the default tag, will have added a penalty of tagPenalties[0]. These should only be positive values since the A* algorithm cannot handle negative penalties.

Note
This array will never be null. If you try to set it to null or with a length which is not 32. It will be set to "new int[0]".
If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath. So you need to change the Seeker value via script, not set this value if you want to change it via script.
See also
Seeker.tagPenalties

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