Public
Movement script that uses ECS.
Warning
This script is still in beta and may change in the future. It aims to be much more robust than AIPath/RichAI, but there may still be rough edges.
This script is a replacement for the AIPath and RichAI scripts.
This script is a movement script. It takes care of moving an agent along a path, updating the path, and so on.
The intended way to use this script is to use these three components:
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 local avoidance (see Local Avoidance).
Supports movement on spherical on non-planar worlds (see Spherical Worlds).
Supports movement on navmesh/recast graphs.
Does not support movement on grid and point graphs at the moment. This will be added in a future update.
Supports time-scales greater than 1. The agent will automatically run multiple simulations 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.
Automatically stops when trying to reach a crowded destination when using local avoidance.
Clamps the agent to the navmesh at all times.
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.
Using ECS components has some downsides, though. 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. Therefore it is recommended to access properties on this script as little as possible. Or, if possible, use an ECS system and access the properties on the ECS components directly (which is much faster).
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.
Differences compared to AIPath and RichAI
In contrast to other movement scripts, this movement script does not use path modifiers at all (except for the seeker's built-in start-end modifier). Instead, this script contains its own internal FunnelModifier which it uses to simplify the path before it follows it.
This script has been written to remedy several inconsistency issues with other scripts. 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 changing destinations, even if it almost never recalculates its path (though the repaired path may not always be optimal).
Best practices for good performance
The main performance foot-gun when using this script, is that accessing properties on it is pretty expensive since it needs to synchronize with entity storage. Therefore it is recommended to access properties on this script as seldom as possible. 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 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.
Public Methods
void
GetRemainingPath
(
List<Vector3> | buffer | 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 script 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);
}
void
Move
(
Vector3 | deltaPosition | 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);
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.
void
SetDestination
(
float3 | destination | |
float3 | facingDirection=default | |
)
Set the position in the world that this agent should move to.
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. How often the agent searches for a new path is controlled by the autoRepath property.
If you are setting a destination and then want to know when the agent has reached that destination then you could either use reachedDestination or reachedEndOfPath. Check the documentation for the respective fields to learn about their differences.
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. Note that reachedDestination and reachedEndOfPath do not take the facing direction into account.
void
SetPath
(
Path | path | The path to follow. |
bool | updateDestinationFromPath=true | If true, the destination property will be set to the end point of the path. If false, the previous destination value will be kept. |
)
Make the AI follow the specified path.
In case the path has not been calculated, the script will call seeker.StartPath to calculate it. 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. This is useful if you want to replace how the AI calculates its paths. Note that if you calculate the path using seeker.StartPath then this script will already pick it up because it is listening for all paths that the Seeker finishes calculating. In that case you do not need to call this function.
If you pass null as a parameter then the current path will be cleared and the agent will stop moving. Note than unless you have also disabled canSearch then the agent will soon recalculate its path and start moving again.
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.
// Disable the automatic path recalculation
ai.canSearch = false;
var pointToAvoid = enemy.position;
// Make the AI flee from the 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);
// If you want to make use of properties like ai.reachedDestination or ai.remainingDistance or similar
// you should also set the destination property to something reasonable.
// Since the agent's own path recalculation is disabled, setting this will not affect how the paths are calculated.
// ai.destination = ...
void
SyncWithEntity
()
Copies all settings from this component to the entity's components.
Note
This is an internal method and you should never need to use it yourself.
void
SyncWithEntity
(
)
Copies all settings from this component to the entity's components.
Note
This is an internal method and you should never need to use it yourself.
void
Teleport
(
Vector3 | newPosition | |
bool | clearPath=true | |
)
Instantly move the agent to a new position.
This will trigger a path recalculation (if clearPath is true, which is the default) so if you want to teleport the agent and change its destination it is recommended that you set the destination before calling this method.
The current path will be cleared by default.
See
Works similarly to Unity's NavmeshAgent.Warp.
SearchPath
Public Variables
Policy for when the agent recalculates its path.
bool
canMove
Enables or disables movement completely.
If you want the agent to stand still, but still react to local avoidance and use gravity: use isStopped instead.
This is also useful if you want to have full control over when the movement calculations run. Take a look at MovementUpdate
Enables or disables debug drawing for this agent.
This is a bitmask with multiple flags so that you can choose exactly what you want to debug.
Vector3
desiredVelocity
Velocity that this agent wants to move with.
Includes gravity and local avoidance if applicable. In world units per second.
Note
The Pathfinding.AILerp movement script doesn't use local avoidance or gravity so this property will always be identical to velocity on that component.
Vector3
desiredVelocityWithoutLocalAvoidance
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);
ai.desiredVelocityWithoutLocalAvoidance = newVelocity;
Note
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.
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
}
Vector3?
endOfPath
End point of path the agent is currently following.
If the agent has no path (or it might not be calculated yet), this will return the destination instead. If the agent has no destination it either it will return (+inf,+inf,+inf).
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.
This is only updated when the path is recalculated.
Entity
entity
Entity which this movement script represents.
An entity will be created when this script is enabled, and destroyed when this script is disabled.
See the documentation for this class to see which components it usually has, and what systems typically affect it.
bool
entityExists
True if this component's entity exists.
This is typically true if the component is active and enabled and the game is running.
Determines which layers the agent will stand on.
The agent will use a raycast each frame to see 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.
bool
hasPath
True if this agent currently has a path that it follows.
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 currently only used if an RVOController is attached to the same GameObject, otherwise it is only used for drawing nice gizmos in the scene view. However since the height value is used for some things, the radius field is always visible for consistency and easier visualization of the character. That said, it may be used for something in a future release.
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.
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.
bool
isTraversingOffMeshLink
True if the agent is currently traversing an off-mesh link.
float
maxSpeed
Max speed in world units per second.
Action
onSearchPath
Called when the agent recalculates its path.
This is called both for automatic path recalculations (see canSearch) and manual ones (see SearchPath).
System.Func<AgentOffMeshLinkTraversalContext, System.Collections.IEnumerator>
onTraverseOffMeshLink
Callback to be called when an agent starts traversing an off-mesh link.
This is called when the agent starts traversing an off-mesh link. The returned coroutine will be used 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. When the coroutine completes, the agent will be assumed to have reached the end of the link and control will be returned to the normal movement code.
bool
pathPending
True if a path is currently being calculated.
Position of the agent.
In world space.
If you want to move the agent you may use Teleport or Move.
float
radius
Radius of the agent in world units.
This is visualized in the scene view as a yellow cylinder around the character.
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.
bool
reachedDestination
True if the ai has reached the destination.
This is a best effort calculation to see if the destination has been reached. For the AIPath/RichAI scripts, this is when the character is within AIPath.endReachedDistance world units from the destination. For the AILerp script it is when the character is at the destination (±a very small margin).
This value will be updated immediately when the destination is changed (in contrast to reachedEndOfPath), however since path requests are asynchronous it will use an approximation until it sees the real path result. What this property does is to check the distance to the end of the current path, and add to that the distance from the end of the path to the destination (i.e. is assumes it is possible to move in a straight line between the end of the current path to the destination) and then checks if that total distance is less than AIPath.endReachedDistance. This property is therefore only a best effort, but it will work well for almost all use cases.
Furthermore it will not report that the destination is reached if the destination is above the head of the character or more than half the height of the character below its feet (so if you have a multilevel building, it is important that you configure the height of the character correctly).
The cases which could be problematic are if an agent is standing next to a very thin wall and the destination suddenly changes to the other side of that thin wall. During the time that it takes for the path to be calculated the agent may see itself as alredy having reached the destination because the destination only moved a very small distance (the wall was thin), even though it may actually be quite a long way around the wall to the other side.
In contrast to reachedEndOfPath, this property is immediately updated 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
}
bool
reachedEndOfPath
True if the agent has reached the end of the current path.
Note that setting the destination does not immediately update the path, nor is there any guarantee that the AI will actually be able to reach the destination that you set. The AI will try to get as close as possible. Often you want to use reachedDestination instead which is easier to work with.
It is very hard to provide a method for detecting if the AI has reached the destination that works across all different games because the destination may not even lie on the navmesh and how that is handled differs from game to game (see also the code snippet in the docs for destination).
float
remainingDistance
Approximate remaining distance along the current path to the end of the path.
The RichAI movement script approximates this distance since it is quite expensive to calculate the real distance. However it will be accurate when the agent is within 1 corner of the destination. You can use GetRemainingPath to calculate the actual remaining path more precisely.
The AIPath and AILerp scripts use a more accurate distance calculation at all times.
If the agent does not currently have a path, then positive infinity will be returned.
Note
This is the distance to the end of the path, which may or may not be at the destination. If the character cannot reach the destination it will try to move as close as possible to it.
Warning
Since path requests are asynchronous, there is a small delay between a path request being sent and this value being updated with the new calculated path.
Rotation of the agent.
In world space.
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 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.
The unit for this field is seconds.
Local avoidance settings.
Vector3
steeringTarget
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.
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.
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 object that this component is attached to will not move instead only the position property and the internal entity will change.
This is useful if you want to control the movement of the character using some other means such as for example root motion but still want the AI to move freely.
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 object that this component is attached to will not rotate instead only the rotation property and the internal entity's rotation will change.
When this is disabled, a gizmos arrow will be drawn in the scene view to indicate the agent's internal rotation.
Actual velocity that the agent is moving with.
In world units per second.
Private/Protected Members
void
AssertEntityExists
()
void
CancelCurrentPathRequest
()
void IAstarAI.
FinalizeMovement
(
)
Move the agent.
To be called as the last step when you are handling movement manually.
The movement will be clamped to the navmesh if applicable (this is done for the RichAI movement script).
void IAstarAI.
MovementUpdate
(
float | deltaTime | time to simulate movement for. Usually set to Time.deltaTime. |
out Vector3 | nextPosition | the position that the agent wants to move to during this frame. |
out Quaternion | nextRotation | 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);
}
void ISerializationCallbackReceiver.
OnAfterDeserialize
()
void ISerializationCallbackReceiver.
OnBeforeSerialize
()
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.
int
OnUpgradeSerializedData
(
int | version | |
bool | unityThread | |
)
Handle serialization backwards compatibility.
void
Reset
()
Handle serialization backwards compatibility.
Color
ShapeGizmoColor = new Color(240/255f, 213/255f, 30/255f)
EntityArchetype
archetype
NativeArray<int>
indicesScratch
MovementSettings
movement = new MovementSettings {
follower = new PIDMovement {
rotationSpeed = 600,
speed = 5,
maxRotationSpeed = 720,
maxOnSpotRotationSpeed = 720,
slowdownTime = 0.5f,
desiredWallDistance = 0.5f,
allowRotatingOnSpot = true,
leadInRadiusWhenApproachingDestination = 1f,
},
movementPlaneSource = MovementPlaneSource.Graph,
stopDistance = 0.2f,
rotationSmoothing = 0f,
groundMask = -1,
isStopped = false,
}
int
scratchReferenceCount = 0
Cached transform component.
Deprecated Members
bool
canSearch
Enables or disables recalculating the path at regular intervals.
Setting this to false does not stop any active path requests from being calculated or stop it from continuing to follow the current path.
Note that this only disables automatic path recalculations. If you call the SearchPath() method a path will still be calculated.