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 for example. Try to use the AIDestinationSetter component instead of setting the destination property manually (at least if you would otherwise set 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
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
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
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
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
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.
Action
onSearchPath
Called when the agent recalculates its path.
This is called both for automatic path recalculations (see canSearch) and manual ones (see SearchPath).
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.
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.
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
float IAstarAI.
maxSpeed
Max speed in world units per second.
MovementSettings
movement = new MovementSettings {
follower = new PIDMovement {
followingStrength = 5,
speed = 5,
maxRotationSpeed = 720,
maxOnSpotRotationSpeed = 720,
slowdownTime = 0.5f,
desiredWallDistance = 0.5f,
allowRotatingOnSpot = true,
},
movementPlaneSource = MovementPlaneSource.Graph,
stopDistance = 0.2f,
}
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.