### Path Setup Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/floodpath Methods for setting up the pathfinding process with start nodes and callbacks. ```csharp void Setup (Vector3 start, OnPathDelegate callback) Setup (start, callback) Protected ``` ```csharp void Setup (GraphNode start, OnPathDelegate callback) Setup (start, callback) Protected ``` -------------------------------- ### Setup Method Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/constantpath Sets up a ConstantPath starting from the specified point. This protected method configures the path with a start point, maximum G score, and a callback delegate. ```APIDOC Setup (start, maxGScore, callback) Sets up a [ConstantPath](constantpath.html) starting from the specified point. Protected void Setup ( | | | | | --- | --- | --- | | [Vector3](https://docs.unity3d.com/ScriptReference/Vector3.html) | start | | | int | maxGScore | | | [OnPathDelegate](pathfinding.html#OnPathDelegate) | callback | | ) Sets up a [ConstantPath](constantpath.html) starting from the specified point. ``` -------------------------------- ### Documentation.html Inclusion Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/changelog The package now includes a 'documentation.html' file providing an offline version of the 'Get Started' tutorial for easier access to documentation. ```html Get Started Tutorial

Astar Pathfinding Project - Get Started

``` -------------------------------- ### Start Method Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/graphupdatescene A placeholder method for performing actions at the start of the component's lifecycle. It's intended for initialization or setup tasks. ```APIDOC Start () Description: Do some stuff at start. ``` -------------------------------- ### Start MultiTargetPath Example (Single Start) Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/seeker Demonstrates how to initiate a MultiTargetPath calculation from a single start point to multiple end points. It shows setting up end points, calling the StartMultiTargetPath method, blocking until calculation is complete, error handling, and visualizing the calculated paths. This feature requires A* Pathfinding Project Pro. ```csharp var endPoints = new Vector3[] { transform.position + Vector3.forward * 5, transform.position + Vector3.right * 10, transform.position + Vector3.back * 15 }; // Start a multi target path, where endPoints is a Vector3[] array. // The pathsForAll parameter specifies if a path to every end point should be searched for // or if it should only try to find the shortest path to any end point. var path = seeker.StartMultiTargetPath(transform.position, endPoints, pathsForAll: true, callback: null); path.BlockUntilCalculated(); if (path.error) { Debug.LogError("Error calculating path: " + path.errorLog); return; } Debug.Log("The closest target was index " + path.chosenTarget); // Draw the path to all targets foreach (var subPath in path.vectorPaths) { for (int i = 0; i < subPath.Count - 1; i++) { Debug.DrawLine(subPath[i], subPath[i+1], Color.green, 10); } } // Draw the path to the closest target for (int i = 0; i < path.vectorPath.Count - 1; i++) { Debug.DrawLine(path.vectorPath[i], path.vectorPath[i+1], Color.red, 10); } ``` -------------------------------- ### Setup Method (Vector3, Vector3, OnPathDelegate) Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/floodpathtracer Sets up the pathfinding calculation with start and end points, and a callback delegate. This protected method is used to initialize a path request. ```APIDOC Setup (start, end, callbackDelegate) Protected void Setup ( | | | | | --- | --- | --- | | [Vector3](https://docs.unity3d.com/ScriptReference/Vector3.html) | start | | | [Vector3](https://docs.unity3d.com/ScriptReference/Vector3.html) | end | | | [OnPathDelegate](pathfinding.html#OnPathDelegate) | callbackDelegate | | ) ``` -------------------------------- ### Path Setup Overloads Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/fleepath Provides multiple overloads for setting up a path calculation. These methods define the start and end points, and optionally include avoidance points, search length, or a callback delegate for path completion. ```APIDOC Setup (start, end, callbackDelegate) Parameters: Vector3 start: The starting point for the path. Vector3 end: The target destination for the path. OnPathDelegate callbackDelegate: The delegate to call when the path is calculated. ``` ```APIDOC Setup (start, avoid, searchLength, callback) Parameters: Vector3 start: The starting point for the path. Vector3 avoid: A point to avoid during path calculation. int searchLength: The maximum number of nodes to search. OnPathDelegate callback: The delegate to call when the path is calculated. ``` ```APIDOC Setup (start, length, callback) Returns: RandomPath: The configured RandomPath object. Parameters: Vector3 start: The starting point for the path. int length: The maximum length of the path to find. OnPathDelegate callback: The delegate to call when the path is calculated. ``` -------------------------------- ### Setup Method (Vector3, FloodPath, OnPathDelegate) Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/floodpathtracer Sets up the pathfinding calculation with a start point, a FloodPath object, and a callback delegate. This protected method is used for flood fill pathfinding initialization. ```APIDOC Setup (start, flood, callback) Protected void Setup ( | | | | | --- | --- | --- | | [Vector3](https://docs.unity3d.com/ScriptReference/Vector3.html) | start | | | [FloodPath](floodpath.html) | flood | | | [OnPathDelegate](pathfinding.html#OnPathDelegate) | callback | | ) ``` -------------------------------- ### Start Method Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/minebotai Starts searching for paths. If this method is overridden, it should typically call base.Start() at the beginning. ```csharp void Start () ``` -------------------------------- ### Start Method Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/richai Starts the pathfinding process or initializes the system. It's recommended to call the base.Start() method when overriding. ```csharp void Start () ``` -------------------------------- ### AstarPath Add/Remove Connection Example Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/linknode Example demonstrating how to add and remove partial connections between nodes using AstarPath. It shows how to get nearest nodes, calculate costs, add connections symmetrically, and verify their existence. ```csharp var node1 = AstarPath.active.GetNearest(transform.position, NNConstraint.None).node; var node2 = AstarPath.active.GetNearest(transform.position + Vector3.right, NNConstraint.None).node; var cost = (uint)(node2.position - node1.position).costMagnitude; // Add connections symmetrically node1.AddPartialConnection(node2, cost, true, true); node2.AddPartialConnection(node1, cost, true, true); // Verify connection exists node1.ContainsOutgoingConnection(node2); // True // Remove connections symmetrically node1.RemovePartialConnection(node2); node2.RemovePartialConnection(node1); ``` -------------------------------- ### Example Scenes Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/changelog Two new example scenes have been added: one demonstrating List Graphs with sample links, and another showcasing Recast Graphs. ```APIDOC Example Scenes: - ListGraphExample: Demonstrates List Graphs and custom links. - RecastGraphExample: Showcases the usage of Recast Graphs. ``` -------------------------------- ### Example Scene Documentation Links Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/changelog Notes the addition of buttons in example scenes linking to corresponding documentation pages. ```APIDOC Example Scene Documentation Links - Feature: Buttons added to all relevant example scenes linking to their corresponding documentation pages. ``` -------------------------------- ### MultiTargetPaths Example Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/changelog Documentation has been updated with an example demonstrating how to use MultiTargetPaths, addressing a previous lack of information. ```APIDOC Pathfinding.MultiTargetPaths - Documentation: Includes a new example scene and usage guide. ``` -------------------------------- ### Initialization and Pathfinding Start Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/aibase Start method initiates pathfinding searches. It's a protected method that should typically call base.Start() if overridden. ```APIDOC Start void Start() - Starts searching for paths. - If you override this method you should in most cases call base.Start() at the start of it. - Protected. ``` -------------------------------- ### Connect Nodes Example Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/levelgridnode Example demonstrating how to connect two graph nodes using the Connect method, calculating cost based on distance. ```csharp // Connect two nodes var node1 = AstarPath.active.GetNearest(transform.position, NNConstraint.None).node; var node2 = AstarPath.active.GetNearest(transform.position + Vector3.right, NNConstraint.None).node; var cost = (uint)(node2.position - node1.position).costMagnitude; GraphNode.Connect(node1, node2, cost, OffMeshLinks.Directionality.TwoWay); ``` -------------------------------- ### SetPath Usage Example Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/followerentity An example demonstrating how to use the SetPath method to make an AI flee from an enemy, constructing a FleePath. ```csharp 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; } } ``` -------------------------------- ### Pathfinding Namespace and Examples Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/changelog Notes the migration of core pathfinding classes into the 'Pathfinding' namespace to prevent naming collisions. Example scripts have also been moved to the 'Pathfinding.Examples' namespace. ```csharp using Pathfinding; using Pathfinding.Examples; ``` -------------------------------- ### AI Script Example Fix Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/changelog Correction in the 'Get Started' tutorial AI script regarding Time.deltaTime usage. ```APIDOC AI Script (Get Started Tutorial) - Fix: Removed multiplication by Time.deltaTime in speed calculation, as it was incorrectly applied. ``` -------------------------------- ### Breadth-First Search (BFS) Example Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/wander Illustrates how to perform a Breadth-First Search starting from a given node to find nearby nodes. It shows how to get the nearest walkable node and then retrieve random points from the BFS result using PathUtilities.GetPointsOnNodes. ```csharp // Find closest walkable node var startNode = [AstarPath](astarpath.html).[active](astarpath.html#active).[GetNearest](astarpath.html#GetNearest2)(transform.position, NNConstraint.Walkable).node; var nodes = PathUtilities.BFS(startNode, nodeDistance); var singleRandomPoint = PathUtilities.GetPointsOnNodes(nodes, 1)[0]; var multipleRandomPoints = PathUtilities.GetPointsOnNodes(nodes, 100); ``` -------------------------------- ### Path Preparation: Prepare and PrepareBase Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/fleepath Methods for initializing pathfinding calculations. `Prepare` performs initial checks and finds start/end nodes. `PrepareBase` handles low-level variable setup before any search operations commence. ```APIDOC Prepare () Prepares the path. Searches for start and end nodes and does some simple checking if a path is at all possible ``` ```APIDOC PrepareBase (pathHandler) Parameters: PathHandler pathHandler: The handler managing pathfinding context. Prepares low level path variables for calculation. Called before a path search will take place. Always called before the Prepare, Initialize and CalculateStep functions ``` -------------------------------- ### InfiniteWorld Example Scene Fix Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/changelog Corrects an issue in the 'InfiniteWorld' example scene where agents could get stuck on obstacles placed with the 'P' key due to incorrect layer settings. ```APIDOC InfiniteWorld Example Scene - Fix: Agents no longer get stuck on obstacles due to incorrect layer settings. - Description: Ensures proper agent navigation in the example scene. ``` -------------------------------- ### Path Initialization and Preparation Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/floodpath Methods used to prepare the pathfinding system before calculation begins. ```csharp void Prepare () Called before the path is started. Called right before Initialize Protected ``` ```csharp void PrepareBase (PathHandler pathHandler) Prepares low level path variables for calculation. Called before a path search will take place. Always called before the Prepare, Initialize and CalculateStep functions Protected ``` -------------------------------- ### Circuit Board Pathfinding with ITraversalProvider Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/circuitboardexamplecs Demonstrates generating sequential paths that do not share nodes, mimicking circuit board routing. It utilizes a custom Blocker class implementing ITraversalProvider to manage traversable nodes. The example requires attaching the script to a GameObject and populating the 'items' array with start and end transforms. ```csharp using UnityEngine; using System.Collections.Generic; using Pathfinding; public class CircuitBoardExample : MonoBehaviour { [System.Serializable] public class Item { public Transform start; public Transform end; } public Item[] items; class Blocker : ITraversalProvider { public HashSet blockedNodes = new HashSet(); public bool CanTraverse (Path path, GraphNode node) { // Override the default logic of which nodes can be traversed return DefaultITraversalProvider.CanTraverse(path, node) && !blockedNodes.Contains(node); } public bool CanTraverse (Path path, GraphNode from, GraphNode to) { return CanTraverse(path, to); } public uint GetTraversalCost (Path path, GraphNode node) { // Use the default costs return DefaultITraversalProvider.GetTraversalCost(path, node); } // This can be omitted in Unity 2021.3 and newer because a default implementation (returning true) can be used there. public bool filterDiagonalGridConnections { get { return true; } } } void Update () { var traversalProvider = new Blocker(); // Calculate all paths in sequence. // It is important that they are not calculated in parallel // as we need to make sure that the paths do not visit the same nodes. // The result may vary significantly depending on the order in which // the paths are calculated. for (int index = 0; index < items.Length; index++) { var item = items[index]; // Create new path object ABPath path = ABPath.Construct(item.start.position, item.end.position); path.traversalProvider = traversalProvider; // Start calculating the path and put the path at the front of the queue AstarPath.StartPath(path, true); // Calculate the path immediately path.BlockUntilCalculated(); // Make sure the remaining paths do not use the same nodes as this one foreach (var node in path.path) { traversalProvider.blockedNodes.Add(node); } // Draw the path in the scene view Color color = AstarMath.IntToColor(index, 0.5f); for (int i = 0; i < path.vectorPath.Count - 1; i++) { Debug.DrawLine(path.vectorPath[i], path.vectorPath[i+1], color); } } } } ``` -------------------------------- ### Documentation and Tutorials Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/changelog Updates to documentation and the addition of new tutorial resources to help users understand and implement pathfinding features. ```APIDOC Documentation - Added: New 'Get Started' video tutorial. - Added: New documentation page and video tutorial for 'Pathfinding in 2D'. ``` -------------------------------- ### Get Remaining Path Example (Simple) Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/iastarai Demonstrates how to retrieve the remaining path points for an agent using the IAstarAI interface. The path is drawn as red lines in the scene. ```csharp var buffer = new System.Collections.Generic.List(); ai.GetRemainingPath(buffer, out bool stale); for (int i = 0; i < buffer.Count - 1; i++) { Debug.DrawLine(buffer[i], buffer[i+1], UnityEngine.Color.red); } ``` -------------------------------- ### C# Pathfinding Example (Conceptual) Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/randompath A conceptual C# code snippet demonstrating how one might use a pathfinding service, setting up a path request and handling the result. ```csharp using Pathfinding; using UnityEngine; public class PathRequester : MonoBehaviour { public Transform target; private Path path; void Start() { // Example: Request a path from current position to target AstarPath.active.RequestPath(transform.position, target.position, OnPathComplete); } void OnPathComplete(Path p) { if (!p.error) { path = p; Debug.Log("Path found: " + path.vectorPath.Count + " nodes."); // You can now use path.vectorPath to move an agent } else { Debug.LogError("Path error: " + p.error); } } // Example of using a method like Setup void RequestCustomPath(Vector3 start, Vector3 end, OnPathDelegate callback) { // Assuming AstarPath.active is accessible and has a Setup method // This is a conceptual example, actual API might differ. // AstarPath.active.Setup(start, end, callback); } } ``` -------------------------------- ### FollowerEntity Off-Mesh Link Traversal Fix Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/changelog Fixes an issue where agents with the FollowerEntity component could get stuck waiting at the start of an off-mesh link if local avoidance or rotation smoothing was enabled. This ensures smoother traversal of off-mesh connections. ```csharp /* Fixed agents with the FollowerEntity component trying to traverse an off-mesh link could get stuck waiting for a long time at the beginning of the link, if either local avoidance or rotation smoothing was enabled. */ ``` -------------------------------- ### NavmeshBase Constructor Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/navmeshbase Initializes a new instance of the NavmeshBase class. ```APIDOC NavmeshBase ( ) Public ##### NavmeshBase () ``` -------------------------------- ### Get Nearest Node with NNConstraint Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/floodpathconstraint An example of calling the GetNearest method on AstarPath to find the node closest to a given point. It utilizes an NNConstraint object, which includes graphMask and other filtering properties, to define search criteria. ```csharp // Find the node closest to somePoint which is either in 'My Grid Graph' OR in 'My Other Grid Graph' var info = AstarPath.active.GetNearest(somePoint, nn); ``` -------------------------------- ### RecastGraph Settings for Tags Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/example_recast_tags Configuration details for a RecastGraph to accurately represent the world with specific settings for agent size and layer masks. This setup is suitable for scenes with flat ground where detailed mesh scanning is required. ```APIDOC RecastGraph: cell size: Reduced to accurately represent the world. character radius: Adjusted to match the size of agents used in the scene. bounds: Modified to fit the world geometry. layer mask: Set to include only the Default layer, as all obstacles are on this layer. ``` -------------------------------- ### Prepare Method Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/floodpathtracer Initializes the path. This protected method is called internally to set up the pathfinding process. ```APIDOC Prepare () Initializes the path. Protected void Prepare () Initializes the path. Traces the path from the start node. ``` -------------------------------- ### Get Remaining Path Example (With Parts) Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/iastarai Demonstrates retrieving the remaining path points and detailed path part information, including off-mesh links. Path segments are drawn in red for node sequences and green for off-mesh links. ```csharp var buffer = new System.Collections.Generic.List(); var parts = new System.Collections.Generic.List(); ai.GetRemainingPath(buffer, parts, out bool stale); foreach (var part in parts) { for (int i = part.startIndex; i < part.endIndex; i++) { Debug.DrawLine(buffer[i], buffer[i+1], part.type == Funnel.PartType.NodeSequence ? UnityEngine.Color.red : UnityEngine.Color.green); }} ``` -------------------------------- ### Request Path and Handle Completion (C#) Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/callingpathfinding Demonstrates how to request a path using the Seeker component and process the result in a callback function. It shows how to get the Seeker, start a path request, and handle potential errors or draw the calculated path. ```csharp void Start () { // Get the seeker component attached to this GameObject var seeker = GetComponent(); // Schedule a new path request from the current position to a position 10 units forward. // When the path has been calculated, the OnPathComplete method will be called, unless it was canceled by another path request seeker.StartPath(transform.position, transform.position + Vector3.forward * 10, OnPathComplete); // Note that the path is NOT calculated at this point // It has just been queued for calculation } void OnPathComplete (Path path) { // The path is now calculated! if (path.error) { Debug.LogError("Path failed: " + path.errorLog); return; } // Cast the path to the path type we were using var abPath = path as ABPath; // Draw the path in the scene view for 10 seconds for (int i = 0; i < abPath.vectorPath.Count - 1; i++) { Debug.DrawLine(abPath.vectorPath[i], abPath.vectorPath[i+1], Color.red, 10); } } ``` -------------------------------- ### SyncTransformsToEntitiesSystem Class and Methods Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/synctransformstoentitiessystem Documentation for the SyncTransformsToEntitiesSystem class, which extends ISystem. It includes methods for initialization, destruction, and updating. ```APIDOC Struct SyncTransformsToEntitiesSystem Extends ISystem Inner Types: SyncTransformsToEntitiesJob Public Methods: OnCreate(ref SystemState state) OnDestroy(ref SystemState state) OnUpdate(ref SystemState systemState) ``` ```APIDOC OnCreate(ref SystemState state) - Initializes the system. - Parameters: - state: The system state. - Returns: void ``` ```APIDOC OnDestroy(ref SystemState state) - Cleans up the system. - Parameters: - state: The system state. - Returns: void ``` ```APIDOC OnUpdate(ref SystemState systemState) - Updates the system. - Parameters: - systemState: The system state. - Returns: void ``` -------------------------------- ### Path Start and End Points Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/fleepath Stores the original and calculated start and end points for the path request. 'originalStartPoint' and 'originalEndPoint' are the user-provided coordinates, while 'startPoint' is the closest point on the start node to the original start point. ```APIDOC ##### [Vector3](https://docs.unity3d.com/ScriptReference/Vector3.html) originalEndPoint End Point exactly as in the path request. ##### [Vector3](https://docs.unity3d.com/ScriptReference/Vector3.html) originalStartPoint Start Point exactly as in the path request. ##### [Vector3](https://docs.unity3d.com/ScriptReference/Vector3.html) startPoint Start point of the path. This is the closest point on the [startNode](abpath.html#startNode) to [originalStartPoint](abpath.html#originalStartPoint) ``` -------------------------------- ### Lightweight Local Avoidance Example Scene Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/changelog Fixed the lightweight local avoidance example scene, which was previously not working. This ensures the example correctly demonstrates local avoidance techniques. ```APIDOC Lightweight Local Avoidance Example - Scene was not working previously. - Fixed to correctly demonstrate local avoidance. ``` -------------------------------- ### Welcome Screen and Documentation Links Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/changelog Details the addition of a welcome screen upon package import, providing easy access to example scenes, documentation, and changelog. ```APIDOC Welcome Screen - Added: A welcome screen appears when importing the package into a new project. - Functionality: Facilitates importing example scenes and provides links to documentation and changelog. ``` -------------------------------- ### Unity Agent and Rendering API Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/lightweightrvo API documentation for Unity methods related to agent creation and frame rendering lifecycle. Includes parameters and return types where specified. ```APIDOC CreateAgent Method Purpose: Creates a single agent entity. Parameters: - archetype: EntityArchetype - buffer: EntityCommandBuffer - position: Vector3 - destination: Vector3 - color: Color - priority: float (defaults to 0.5f) Returns: Implicitly creates an agent entity. ``` ```APIDOC OnBeginFrameRendering Method Purpose: Called at the beginning of the frame rendering process. Parameters: - ctx: ScriptableRenderContext - cameras: Camera[] Returns: void ``` ```APIDOC OnDestroy Method Purpose: Called when the associated object is being destroyed. Parameters: None Returns: void ``` ```APIDOC PreCull Method Purpose: Called before the culling process for a camera. Parameters: - camera: Camera Returns: void ``` ```APIDOC uniformDistance Method Purpose: Calculates a uniform distance, likely for spatial calculations. Parameters: - radius: float Returns: float ``` -------------------------------- ### Interactable Class Documentation (C#) Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/interactable Example script for handling interactable objects in the example scenes. It implements a simple state machine for actions. Note: This is an example script; consider other state machine solutions for complex games. ```C# public class Interactable : VersionedMonoBehaviour, IOffMeshLinkHandler, IOffMeshLinkStateMachine { // Example script for handling interactable objects in the example scenes. // It implements a very simple and lightweight state machine. // Note // This is an example script intended for the A* Pathfinding Project's example scenes. If you need a proper state machine for your game, you may be better served by other state machine solutions on the Unity Asset Store. // It works by keeping a linear list of states, each with an associated action. When an agent interacts with this object, it immediately does the first action in the list. Once that action is done, it will do the next action and so on. // Some actions may cancel the whole interaction. For example the MoveTo action will cancel the interaction if the agent suddenly had its destination to something else. Presumably because the agent was interrupted by something. // If this component is added to the same GameObject as a NodeLink2 component, the interactable will automatically trigger when the agent traverses the link. Some components behave differently when used during an off-mesh link component. For example the MoveToAction will move the agent without taking the navmesh into account (becoming a thin wrapper for AgentOffMeshLinkTraversalContext.MoveTowards). } ``` -------------------------------- ### UpdateStart: Updates path start point and repairs Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/pathtracer Updates the start point of the path, clamping it to the graph and repairing the path if necessary. It returns the new, clamped start point. This operation might mark the path as stale if repair fails. ```C# Vector3 UpdateStart ( Vector3 position, RepairQuality quality, NativeMovementPlane movementPlane, ITraversalProvider traversalProvider, Path path ) ``` -------------------------------- ### AI Helper Components Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/getstarted Documentation for essential helper components that simplify AI pathfinding setup. These components manage path requests and target assignment, allowing for easier integration into game logic. ```APIDOC Seeker: - Description: A core component responsible for requesting paths from the pathfinding system. It acts as an interface between AI agents and the graph. - Functionality: Initiates path requests, handles path modifiers (e.g., smoothing, raycast simplification). - Usage: Attach to any GameObject that needs to find paths. - Related: AIPath, RichAI, AILerp. AIDestinationSetter: - Description: A simple helper script that automatically sets the destination for an AI agent. - Functionality: Assigns a target GameObject to an AI's movement script (e.g., AIPath). - Parameters: - target: The GameObject the AI should move towards. - Usage: Attach to an AI GameObject and assign a 'Target' GameObject to its 'target' field. - Related: AIPath, Seeker. ``` -------------------------------- ### Path Calculation and Scheduling Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/pathtracer Demonstrates how to schedule a path calculation using ABPath.Construct and AstarPath.StartPath, and how to process the result in a callback. ```csharp using Pathfinding; using Pathfinding.Drawing; using Pathfinding.Util; using Unity.Collections; using Unity.Mathematics; using UnityEngine; public class PathTracerTest : MonoBehaviour { PathTracer tracer; ABPath lastCalculatedPath; NativeMovementPlane movementPlane => new NativeMovementPlane(Quaternion.identity); void OnEnable () { tracer = new PathTracer(Allocator.Persistent); } void OnDisable () { // Release all unmanaged memory from the path tracer, to avoid memory leaks tracer.Dispose(); } void Start () { // Schedule a path calculation to a point ahead of this object var path = ABPath.Construct(transform.position, transform.position + transform.forward*10, (p) => { // This callback will be called when the path has been calculated var path = p as ABPath; if (path.error) { // The path could not be calculated Debug.LogError("Could not calculate path"); return; } // Split the path into normal sequences of nodes, and off-mesh links var parts = Funnel.SplitIntoParts(path); // Assign the path to the PathTracer tracer.SetPath(parts, path.path, path.originalStartPoint, path.originalEndPoint, movementPlane, path.traversalProvider, path); lastCalculatedPath = path; }); AstarPath.StartPath(path); } void Update () { if (lastCalculatedPath == null || !tracer.isCreated) return; // Repair the path to start from the transform's position // If you move the transform around in the scene view, you'll see the path update in real time tracer.UpdateStart(transform.position, PathTracer.RepairQuality.High, movementPlane, lastCalculatedPath.traversalProvider, lastCalculatedPath); // Get up to the next 10 corners of the path var buffer = new NativeList(Allocator.Temp); NativeArray scratchArray = default; tracer.GetNextCorners(buffer, 10, ref scratchArray, Allocator.Temp, lastCalculatedPath.traversalProvider, lastCalculatedPath); // Draw the next 10 corners of the path in the scene view using (Draw.WithLineWidth(2)) { Draw.Polyline(buffer.AsArray(), Color.red); } // Release all temporary unmanaged memory buffer.Dispose(); scratchArray.Dispose(); } } ``` -------------------------------- ### Navmesh Cutting Example Scene Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/changelog A new example scene named 'Door2' has been added, which demonstrates the usage of the NavmeshCut component. ```C# // New example scene Door2 which uses the NavmeshCut component. ``` -------------------------------- ### PushStart Method (Instance) Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/funnelstate Adds a start portal to the funnel. Takes two Vector3 points representing the new left and right portal endpoints. ```APIDOC PushStart(Vector3 newLeftPortal, Vector3 newRightPortal) - Adds a start portal to the funnel. - Parameters: - newLeftPortal: The new left portal endpoint (Vector3). - newRightPortal: The new right portal endpoint (Vector3). ``` -------------------------------- ### TileSizeX Example Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/recastgraph Demonstrates the declaration and default assignment of the tileSizeX integer property in C#. ```csharp int tileSizeX = 128; ``` -------------------------------- ### Example Scene Fixes Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/changelog Addresses issues in example scenes, such as missing animations, stray deprecated components, and missing scripts. ```APIDOC Example Scenes - Fixed: A missing script in the turnbased example scene causing warnings. - Fixed: Animations for the agent character were missing in some newer Unity versions, potentially causing exceptions. - Removed: Stray uses of the old and deprecated GUIText component, which could cause descriptions for some example scenes not to show up. ``` -------------------------------- ### Path Settings and Waiting Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/abpath Allows copying path settings and waiting for path calculation completion. ```APIDOC void UseSettings ( [PathRequestSettings](pathrequestsettings.html) settings ) - Copies the given settings into this path. - Parameters: - settings: The path request settings to apply. void WaitForPath () - Waits until this path has been calculated and returned. ``` -------------------------------- ### Example Scene: Recast Graph with Tags Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/example_recast_tags A Unity C# example demonstrating the use of tags for pathfinding in a Recast graph. It shows how to set up distinct traversable areas (red and blue corridors) and agents that can only navigate their respective colored paths. ```C# // This is a conceptual representation based on the documentation. // Actual code would involve setting up GameObjects with AstarPath, RecastGraph, RecastMeshObj, and FollowerEntity components. // Example of setting up a RecastGraph component (in Unity Editor or via script): // RecastGraph graph = AstarPath.active.astarData.graphs[0] as RecastGraph; // graph.cellSize = 0.5f; // Example value // graph.characterRadius = 0.5f; // Example value // graph.layerMask = 1 << LayerMask.NameToLayer("Default"); // Example of setting up a RecastMeshObj component on a GameObject: // RecastMeshObj rmo = gameObject.AddComponent(); // rmo.surfaceType = RecastMeshObj.SurfaceType.WalkableWithTag; // rmo.tag = "Red"; // or "Blue" // Example of setting up a FollowerEntity component on an agent GameObject: // FollowerEntity follower = gameObject.AddComponent(); // follower.tagPenalties = new TagMask(); // Initialize TagMask // follower.tagPenalties.SetFlag("Blue", false); // Make agent avoid "Blue" tagged areas ``` -------------------------------- ### RWLock Job Integration Example Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/rwlock Demonstrates how to use the RWLock's asynchronous methods to manage dependencies between the main thread and Unity Jobs, ensuring data consistency. ```csharp var readLock = AstarPath.active.LockGraphDataForReading(); var handle = new MyJob { ... }.Schedule(readLock.dependency); readLock.UnlockAfter(handle); ``` -------------------------------- ### RVO Example Scenes Fix Source: https://arongranberg.com/astar/documentation/5_1_1/_0e39bc772/changelog Corrected a regression introduced in version 4.2.16 that caused RVO example scenes to not function properly. ```C# // Fix for RVO example scenes not working properly. // Fixed RVO example scenes not working properly (regression introduced in 4.2.16). ```