Of note is that this component shouldn't be used with a Seeker component. It instead has its own settings for pathfinding, which are stored in the pathfindingSettings field.
Features
Uses Unity's ECS (Entity Component System) to move the agent. This means it is highly-performant and is able to utilize multiple threads.
Supports movement on spherical on non-planar worlds (see Spherical Worlds).
Supports movement on grid graphs as well as navmesh/recast graphs.
Does not support movement on point graphs at the moment. This may be added in a future update.
Supports time-scales greater than 1. The agent will automatically run multiple simulation steps per frame if the time-scale is greater than 1, to ensure stability.
Supports off-mesh links. Subscribe to the onTraverseOffMeshLink event to handle this.
Knows which node it is traversing at all times (see currentNode).
Automatically stops when trying to reach a crowded destination when using local avoidance.
Clamps the agent to the navmesh at all times.
Follows paths very smoothly.
Can keep a desired distance to walls.
Can approach its destination with a desired facing direction.
ECS
This script uses Unity's ECS (Entity Component System) to move the agent. This means it is highly-performant and is able to utilize multiple threads. Internally, an entity is created for the agent with the following components:
Then this script barely does anything by itself. It is a thin wrapper around the ECS components. Instead, actual movement calculations are carried out by the following systems:
In fact, as long as you create the appropriate ECS components, you do not even need this script. You can use the systems directly.
This is not a baked component. That is, this script will continue to work even in standalone games. It is designed to be easily used without having to care too much about the underlying ECS implementation.
This movement script has been written to remedy several inconsistency issues with other movement scrips, to provide very smooth movement, and "just work" for most games.
For example, it goes to great lengths to ensure that the reachedDestination and reachedEndOfPath properties are as accurate as possible at all times, even before it has had time to recalculate its path to account for a new destination. It does this by locally repairing the path (if possible) immediately when the destination changes instead of waiting for a path recalculation. This also has a bonus effect that the agent can often work just fine with moving targets, even if it almost never recalculates its path (though the repaired path may not always be optimal), and it leads to very responsive movement.
In contrast to other movement scripts, this movement script does not use path modifiers at all. Instead, this script contains its own internal FunnelModifier which it uses to simplify the path before it follows it. In also doesn't use a separate RVOController component for local avoidance, but instead it stores local avoidance settings in rvoSettings.
Best practices for good performance
Using ECS components has some downsides. Accessing properties on this script is significantly slower compared to accessing properties on other movement scripts. This is because on each property access, the script has to make sure no jobs are running concurrently, which is a relatively expensive operation. Slow is a relative term, though. This only starts to matter if you have lots of agents, maybe a hundred or so. So don't be scared of using it.
But if you have a lot of agents, it is recommended to not access properties on this script more often than required. Avoid setting fields to the same value over and over again every frame, for example. If you have a moving target, try to use the AIDestinationSetter component instead of setting the destination property manually, as that is faster than setting the destination property every frame.
You can instead write custom ECS systems to access the properties on the ECS components directly. This is much faster. For example, if you want to make the agent follow a particular entity, you could create a new DestinationEntity component which just holds an entity reference, and then create a system that every frame copies that entity's position to the DestinationPoint.destination field (a component that this entity will always have).
This script has some optional parts. Local avoidance, for example. Local avoidance is used to make sure that agents do not overlap each other. However, if you do not need it, you can disable it to improve performance.
The buffer will be cleared and replaced with the path. The first point is the current position of the agent.
out bool
stale
May be true if the path is invalid in some way. For example if the agent has no path or (for the RichAI/FollowerEntity components only) if the agent has detected that some nodes in the path have been destroyed.
)
Fills buffer with the remaining path.
var buffer = new List<Vector3>();
ai.GetRemainingPath(buffer, out bool stale); for (int i = 0; i < buffer.Count - 1; i++) { Debug.DrawLine(buffer[i], buffer[i+1], Color.red); }
Direction and distance to move the agent in world space.
)
Move the agent.
This is intended for external movement forces such as those applied by wind, conveyor belts, knockbacks etc.
Some movement scripts may ignore this completely (notably the AILerp script) if it does not have any concept of being moved externally.
The agent will not be moved immediately when calling this method. Instead this offset will be stored and then applied the next time the agent runs its movement calculations (which is usually later this frame or the next frame). If you want to move the agent immediately then call: ai.Move(someVector); ai.FinalizeMovement(ai.position, ai.rotation);
SearchPath
()
Recalculate the current path.
Public
void
SearchPath ()
Recalculate the current path.
You can for example use this if you want very quick reaction times when you have changed the destination so that the agent does not have to wait until the next automatic path recalculation (see canSearch).
If there is an ongoing path calculation, it will be canceled, so make sure you leave time for the paths to get calculated before calling this function again. A canceled path will show up in the log with the message "Canceled by script" (see Seeker.CancelCurrentPathRequest).
If no destination has been set yet then nothing will be done.
Note
The path result may not become available until after a few frames. During the calculation time the pathPending property will return true.
Set the position in the world that this agent should move to.
Public
void
SetDestination (
float3
destination
float3
facingDirection=default
)
Set the position in the world that this agent should move to.
This method will immediately try to repair the path if the agent already has a path. This will also immediately update properties like reachedDestination, reachedEndOfPath and remainingDistance. The agent may do a full path recalculation if the local repair was not sufficient, but this will at earliest happen in the next simulation step.
If you are setting a destination and want to know when the agent has reached that destination, then you could use either reachedDestination or reachedEndOfPath.
You may also set a facing direction for the agent. If set, the agent will try to approach the destination point with the given heading. reachedDestination and reachedEndOfPath will only return true once the agent is approximately facing the correct direction. The MovementSettings.follower.leadInRadiusWhenApproachingDestination field controls how wide an arc the agent will try to use when approaching the destination.
The following video shows three agents, one with no facing direction set, and then two agents with varying values of the lead in radius.
IEnumerator Start () { ai.SetDestination(somePoint, Vector3.right); // Wait until the AI has reached the destination and is rotated to the right in world space while (!ai.reachedEndOfPath) { yield return null; } // The agent has reached the destination now }
If true, the destination property will be set to the end point of the path. If false, the previous destination value will be kept. If you pass a path which has no well defined destination before it is calculated (e.g. a MultiTargetPath or RandomPath), then the destination will be first be cleared, but once the path has been calculated, it will be set to the end point of the path.
)
Make the AI follow the specified path.
In case the path has not been calculated, the script will schedule the path to be calculated. This means the AI may not actually start to follow the path until in a few frames when the path has been calculated. The pathPending field will, as usual, return true while the path is being calculated.
In case the path has already been calculated, it will immediately replace the current path the AI is following.
If you pass null path, then the current path will be cleared and the agent will stop moving. The agent will also abort traversing any off-mesh links it is currently traversing. Note than unless you have also disabled canSearch, then the agent will soon recalculate its path and start moving again.
Note
Stopping the agent by passing a null path works. But this will stop the agent instantly, and it will not be able to use local avoidance or know its place on the navmesh. Usually it's better to set isStopped to false, which will make the agent slow down smoothly.
You can disable the automatic path recalculation by setting the canSearch field to false.
Note
This call will be ignored if the agent is currently traversing an off-mesh link. Furthermore, if the agent starts traversing an off-mesh link, the current path request will be canceled (if one is currently in progress).
IEnumerator Start () { var pointToAvoid = enemy.position; // Make the AI flee from an enemy. // The path will be about 20 world units long (the default cost of moving 1 world unit is 1000). var path = FleePath.Construct(ai.position, pointToAvoid, 1000 * 20); ai.SetPath(path);
while (!ai.reachedEndOfPath) { yield return null; } }
This method is preferred for long distance teleports. If you only move the agent a very small distance (so that it is reasonable that it can keep its current path), then setting the position property is preferred. Setting the position property very far away from the agent could cause the agent to fail to move the full distance, as it can get blocked by the navmesh.
If true, the destination property will be set to the end point of the path. If false, the previous destination value will be kept. If you pass a path which has no well defined destination before it is calculated (e.g. a MultiTargetPath or RandomPath), then the destination will be first be cleared, but once the path has been calculated, it will be set to the end point of the path.
)
Make the AI follow the specified path.
In case the path has not been calculated, the script will schedule the path to be calculated. This means the AI may not actually start to follow the path until in a few frames when the path has been calculated. The pathPending field will, as usual, return true while the path is being calculated.
In case the path has already been calculated, it will immediately replace the current path the AI is following.
If you pass null path, then the current path will be cleared and the agent will stop moving. The agent will also abort traversing any off-mesh links it is currently traversing. Note than unless you have also disabled canSearch, then the agent will soon recalculate its path and start moving again.
Note
Stopping the agent by passing a null path works. But this will stop the agent instantly, and it will not be able to use local avoidance or know its place on the navmesh. Usually it's better to set isStopped to false, which will make the agent slow down smoothly.
You can disable the automatic path recalculation by setting the canSearch field to false.
Note
This call will be ignored if the agent is currently traversing an off-mesh link. Furthermore, if the agent starts traversing an off-mesh link, the current path request will be canceled (if one is currently in progress).
IEnumerator Start () { var pointToAvoid = enemy.position; // Make the AI flee from an enemy. // The path will be about 20 world units long (the default cost of moving 1 world unit is 1000). var path = FleePath.Construct(ai.position, pointToAvoid, 1000 * 20); ai.SetPath(path);
while (!ai.reachedEndOfPath) { yield return null; } }
Velocity that this agent wants to move with before taking local avoidance into account.
Includes gravity. In world units per second.
Setting this property will set the current velocity that the agent is trying to move with, including gravity. This can be useful if you want to make the agent come to a complete stop in a single frame or if you want to modify the velocity in some way.
// Set the velocity to zero, but keep the current gravity var newVelocity = new Vector3(0, ai.desiredVelocityWithoutLocalAvoidance.y, 0);
The Pathfinding.AILerp movement script doesn't use local avoidance so this property will always be identical to velocity on that component.
Warning
Trying to set this property on an AILerp component will throw an exception since its velocity cannot meaningfully be changed abitrarily.
If you are not using local avoidance then this property will in almost all cases be identical to desiredVelocity plus some noise due to floating point math.
Position in the world that this agent should move to.
Public
Vector3?
destination
Position in the world that this agent should move to.
If no destination has been set yet, then (+infinity, +infinity, +infinity) will be returned.
Note that setting this property does not immediately cause the agent to recalculate its path. So it may take some time before the agent starts to move towards this point. Most movement scripts have a repathRate field which indicates how often the agent looks for a new path. You can also call the SearchPath method to immediately start to search for a new path. Paths are calculated asynchronously so when an agent starts to search for path it may take a few frames (usually 1 or 2) until the result is available. During this time the pathPending property will return true.
If you are setting a destination and then want to know when the agent has reached that destination then you could either use reachedDestination (recommended) or check both pathPending and reachedEndOfPath. Check the documentation for the respective fields to learn about their differences.
IEnumerator Start () { ai.destination = somePoint; // Start to search for a path to the destination immediately ai.SearchPath(); // Wait until the agent has reached the destination while (!ai.reachedDestination) { yield return null; } // The agent has reached the destination now } IEnumerator Start () { ai.destination = somePoint; // Start to search for a path to the destination immediately // Note that the result may not become available until after a few frames // ai.pathPending will be true while the path is being calculated ai.SearchPath(); // Wait until we know for sure that the agent has calculated a path to the destination we set above while (ai.pathPending || !ai.reachedEndOfPath) { yield return null; } // The agent has reached the destination now } Position in the world that this agent should move to.
If no destination has been set yet, then (+infinity, +infinity, +infinity) will be returned.
Setting this property will immediately try to repair the path if the agent already has a path. This will also immediately update properties like reachedDestination, reachedEndOfPath and remainingDistance.
The agent may do a full path recalculation if the local repair was not sufficient, but this will at earliest happen in the next simulation step.
IEnumerator Start () { ai.destination = somePoint; // Wait until the AI has reached the destination while (!ai.reachedEndOfPath) { yield return null; } // The agent has reached the destination now }
See
SetDestination, which also allows you to set a facing direction for the agent.
enableGravity
Enables or disables gravity.
Public
bool
enableGravity
Enables or disables gravity.
If gravity is enabled, the agent will accelerate downwards, and use a raycast to check if it should stop falling.
End point of path the agent is currently following.
If the agent has no path (or if it's not calculated yet), this will return the destination instead. If the agent has no destination it will return the agent's current position.
The end of the path is usually identical or very close to the destination, but it may differ if the path for example was blocked by a wall, so that the agent couldn't get any closer.
The agent will use a raycast each frame to check if it should stop falling.
This layer mask should ideally not contain the agent's own layer, if the agent has a collider, as this may cause it to try to stand on top of itself.
hasPath
True if this agent currently has a valid path that it follows.
Public
bool
hasPath
True if this agent currently has a valid path that it follows.
This is true if the agent has a path and the path is not stale.
A path may become stale if the graph is updated close to the agent and it hasn't had time to recalculate its path yet.
height
Height of the agent in world units.
Public
float
height
Height of the agent in world units.
This is visualized in the scene view as a yellow cylinder around the character.
This value is used for various heuristics, and for visualization purposes. For example, the destination is only considered reached if the destination is not above the agent's head, and it's not more than half the agent's height below its feet.
If local lavoidance is enabled, this is also used to filter out collisions with agents and obstacles that are too far above or below the agent.
isStopped
Gets or sets if the agent should stop moving.
Public
bool
isStopped
Gets or sets if the agent should stop moving.
If this is set to true the agent will immediately start to slow down as quickly as it can to come to a full stop. The agent will still react to local avoidance and gravity (if applicable), but it will not try to move in any particular direction.
The current path of the agent will not be cleared, so when this is set to false again the agent will continue moving along the previous path.
This is a purely user-controlled parameter, so for example it is not set automatically when the agent stops moving because it has reached the target. Use reachedEndOfPath for that.
If this property is set to true while the agent is traversing an off-mesh link (RichAI script only), then the agent will continue traversing the link and stop once it has completed it.
Note
This is not the same as the canMove setting which some movement scripts have. The canMove setting disables movement calculations completely (which among other things makes it not be affected by local avoidance or gravity). For the AILerp movement script which doesn't use gravity or local avoidance anyway changing this property is very similar to changing canMove.
The steeringTarget property will continue to indicate the point which the agent would move towards if it would not be stopped.
isTraversingOffMeshLink
True if the agent is currently traversing an off-mesh link.
Public
bool
isTraversingOffMeshLink
True if the agent is currently traversing an off-mesh link.
This is typically the ground plane, which will be the XZ plane in a 3D game, and the XY plane in a 2D game. Ultimately it depends on the graph orientation.
If you are doing pathfinding on a spherical world (see Spherical Worlds), the the movement plane will be the tangent plane of the sphere at the agent's position.
If the off-mesh link is destroyed while the agent is traversing it, this property will still return the link. But be careful about accessing properties like OffMeshLinkSource.gameObject, as that may refer to a destroyed gameObject.
Callback to be called when an agent starts traversing an off-mesh link.
The handler will be called when the agent starts traversing an off-mesh link. It allows you to to control the agent for the full duration of the link traversal.
Use the passed context struct to get information about the link and to control the agent.
namespace Pathfinding.Examples { public class FollowerJumpLink : MonoBehaviour, IOffMeshLinkHandler, IOffMeshLinkStateMachine { // Register this class as the handler for off-mesh links when the component is enabled void OnEnable() => GetComponent<NodeLink2>().onTraverseOffMeshLink = this; void OnDisable() => GetComponent<NodeLink2>().onTraverseOffMeshLink = null;
IEnumerable IOffMeshLinkStateMachine.OnTraverseOffMeshLink (AgentOffMeshLinkTraversalContext ctx) { var start = (Vector3)ctx.linkInfo.relativeStart; var end = (Vector3)ctx.linkInfo.relativeEnd; var dir = end - start;
// Disable local avoidance while traversing the off-mesh link. // If it was enabled, it will be automatically re-enabled when the agent finishes traversing the link. ctx.DisableLocalAvoidance();
// Move and rotate the agent to face the other side of the link. // When reaching the off-mesh link, the agent may be facing the wrong direction. while (!ctx.MoveTowards( position: start, rotation: Quaternion.LookRotation(dir, ctx.movementPlane.up), gravity: true, slowdown: true).reached) { yield return null; }
var bezierP0 = start; var bezierP1 = start + Vector3.up*5; var bezierP2 = end + Vector3.up*5; var bezierP3 = end; var jumpDuration = 1.0f;
// Animate the AI to jump from the start to the end of the link for (float t = 0; t < jumpDuration; t += ctx.deltaTime) { ctx.transform.Position = AstarSplines.CubicBezier(bezierP0, bezierP1, bezierP2, bezierP3, Mathf.SmoothStep(0, 1, t / jumpDuration)); yield return null; } } } }
Warning
Off-mesh links can be destroyed or disabled at any moment. The built-in code will attempt to make the agent continue following the link even if it is destroyed, but if you write your own traversal code, you should be aware of this.
You can alternatively set the corresponding property property on the off-mesh link ( NodeLink2.onTraverseOffMeshLink) to specify a callback for a specific off-mesh link.
Note
The agent's off-mesh link handler takes precedence over the link's off-mesh link handler, if both are set.
For 3D games you most likely want the ZAxisIsForward option as that is the convention for 3D games.
For 2D games you most likely want the YAxisIsForward option as that is the convention for 2D games.
When using ZAxisForard, the +Z axis will be the forward direction of the agent, +Y will be upwards, and +X will be the right direction.
When using YAxisForward, the +Y axis will be the forward direction of the agent, +Z will be upwards, and +X will be the right direction.
If you want to move the agent you may use Teleport or Move.
radius
Radius of the agent in world units.
Public
float
radius
Radius of the agent in world units.
This is visualized in the scene view as a yellow cylinder around the character.
Note that this does not affect pathfinding in any way. The graph used completely determines where the agent can move.
Note
The Pathfinding.AILerp script doesn't really have any use of knowing the radius or the height of the character, so this property will always return 0 in that script.
The agent considers the destination reached when it is within stopDistance world units from the destination. Additionally, the destination must not be above the agent's head, and it must not be more than half the agent's height below its feet.
If a facing direction was specified when setting the destination, this will only return true once the agent is approximately facing the correct orientation.
This value will be updated immediately when the destination is changed.
IEnumerator Start () { ai.destination = somePoint; // Start to search for a path to the destination immediately ai.SearchPath(); // Wait until the agent has reached the destination while (!ai.reachedDestination) { yield return null; } // The agent has reached the destination now }
Note
The agent may not be able to reach the destination. In that case this property may never become true. Sometimes reachedEndOfPath is more appropriate.
True if the agent has reached the end of the current path.
Public
bool
reachedEndOfPath
True if the agent has reached the end of the current path.
The agent considers the end of the path reached when it is within stopDistance world units from the end of the path. Additionally, the end of the path must not be above the agent's head, and it must not be more than half the agent's height below its feet.
If a facing direction was specified when setting the destination, this will only return true once the agent is approximately facing the correct orientation.
This value will be updated immediately when the destination is changed.
Note
Reaching the end of the path does not imply that it has reached its desired destination, as the destination may not even be possible to reach. Sometimes reachedDestination is more appropriate.
Approximate remaining distance along the current path to the end of the path.
Public
float
remainingDistance
Approximate remaining distance along the current path to the end of the path.
The agent does not know the true distance at all times, so this is an approximation. It tends to be a bit lower than the true distance.
Note
This is the distance to the end of the path, which may or may not be the same as the destination. If the character cannot reach the destination it will try to move as close as possible to it.
This value will update immediately if the destination property is changed, or if the agent is moved using the position property or the Teleport method.
If the agent has no path, or if the current path is stale (e.g. if the graph has been updated close to the agent, and it hasn't had time to recalculate its path), this will return positive infinity.
The entity internally always treats the Z axis as forward, but this property respects the orientation field. So it will return either a rotation with the Y axis as forward, or Z axis as forward, depending on the orientation field.
This will return the agent's rotation even if updateRotation is false.
How much to smooth the visual rotation of the agent.
Public
float
rotationSmoothing
How much to smooth the visual rotation of the agent.
This does not affect movement, but smoothes out how the agent rotates visually.
Recommended values are between 0.0 and 0.5. A value of zero will disable smoothing completely.
The smoothing is done primarily using an exponential moving average, but with a small linear term to make the rotation converge faster when the agent is almost facing the desired direction.
Adding smoothing will make the visual rotation of the agent lag a bit behind the actual rotation. Too much smoothing may make the agent seem sluggish, and appear to move sideways.
Point on the path which the agent is currently moving towards.
This is usually a point a small distance ahead of the agent or the end of the path.
If the agent does not have a path at the moment, then the agent's current position will be returned.
stopDistance
How far away from the destination should the agent aim to stop, in world units.
Public
float
stopDistance
How far away from the destination should the agent aim to stop, in world units.
If the agent is within this distance from the destination point it will be considered to have reached the destination.
Even if you want the agent to stop precisely at a given point, it is recommended to keep this slightly above zero. If it is exactly zero, the agent may have a hard time deciding that it has actually reached the end of the path, due to floating point errors and such.
Note
This will not be multiplied the agent's scale.
updatePosition
Determines if the character's position should be coupled to the Transform's position.
Public
bool
updatePosition
Determines if the character's position should be coupled to the Transform's position.
If false then all movement calculations will happen as usual, but the GameObject that this component is attached to will not move. Instead, only the position property and the internal entity's position will change.
This is useful if you want to control the movement of the character using some other means, such as root motion, but still want the AI to move freely.
See
canMove which in contrast to this field will disable all movement calculations.
Determines if the character's rotation should be coupled to the Transform's rotation.
Public
bool
updateRotation
Determines if the character's rotation should be coupled to the Transform's rotation.
If false then all movement calculations will happen as usual, but the GameObject that this component is attached to will not rotate. Instead, only the rotation property and the internal entity's rotation will change.
You can enable PIDMovement.DebugFlags.Rotation in debugFlags to draw a gizmos arrow in the scene view to indicate the agent's internal rotation.
the rotation that the agent wants to rotate to during this frame.
)
Calculate how the character wants to move during this frame.
Note that this does not actually move the character. You need to call FinalizeMovement for that. This is called automatically unless canMove is false.
To handle movement yourself you can disable canMove and call this method manually. This code will replicate the normal behavior of the component: void Update () { // Disable the AIs own movement code ai.canMove = false; Vector3 nextPosition; Quaternion nextRotation; // Calculate how the AI wants to move ai.MovementUpdate(Time.deltaTime, out nextPosition, out nextRotation); // Modify nextPosition and nextRotation in any way you wish // Actually move the AI ai.FinalizeMovement(nextPosition, nextRotation); }
OnDisable
()
Called when the component is disabled or about to be destroyed.
Private
void
OnDisable ()
Called when the component is disabled or about to be destroyed.
This is also called by Unity when an undo/redo event is performed. This means that when an undo event happens the entity will get destroyed and then re-created.