### Unity Scene Setup for A* Pathfinding Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/getstarted Instructions for creating a new Unity scene, adding a plane as ground, and creating cubes as obstacles. It also covers creating and assigning 'Ground' and 'Obstacles' layers to scene objects for proper pathfinding interaction. ```APIDOC Scene Setup: - Create new scene: "PathfindingTest" - Add Plane: - Position: (0,0,0) - Scale: (10,10,10) - Layer: "Ground" (create if not exists: Edit → Project Settings → Tags) - Add Cubes (Obstacles): - Place on plane - Layer: "Obstacles" (create if not exists) ``` -------------------------------- ### Setup Method Overloads Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/fleepath Configures the path with start and end points, and a callback delegate. Multiple overloads exist to support different path setup scenarios, such as specifying an avoidance point or a search length. ```APIDOC Protected void Setup( Vector3 start, Vector3 end, OnPathDelegate callbackDelegate ) ``` ```APIDOC Protected void Setup( Vector3 start, Vector3 avoid, int searchLength, OnPathDelegate callback ) ``` ```APIDOC Protected RandomPath Setup( Vector3 start, int length, OnPathDelegate callback ) ``` -------------------------------- ### Setup Method (Vector3 start) Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/floodpath This protected method sets up the path with a Vector3 starting point and a callback delegate. ```APIDOC void Setup ( start: Vector3, callback: OnPathDelegate ) ``` -------------------------------- ### Setup Method (GraphNode start) Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/floodpath This protected method sets up the path with a GraphNode starting point and a callback delegate. ```APIDOC void Setup ( start: GraphNode, callback: OnPathDelegate ) ``` -------------------------------- ### Setup Method (Vector3, Vector3, OnPathDelegate) Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/randompath Sets up the path with a start point, end point, and a callback delegate. ```APIDOC void Setup( Vector3 start, Vector3 end, OnPathDelegate callbackDelegate ) ``` -------------------------------- ### Setup Method (Vector3, int, OnPathDelegate) Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/randompath Sets up a random path with a start point, a specified length, and a callback delegate. ```APIDOC RandomPath Setup( Vector3 start, int length, OnPathDelegate callback ) ``` -------------------------------- ### Setup Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/abpath Sets up the path with start and end points, and a callback delegate. This method is protected. ```APIDOC void Setup( Vector3 start, Vector3 end, OnPathDelegate callbackDelegate ) ``` -------------------------------- ### Seeker Component Overview Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/getstarted Documentation for the Seeker component, which works in conjunction with movement scripts. It is responsible for calculating paths based on requests from the movement script and returning the results. ```APIDOC Seeker Component: Purpose: Calculates paths for agents. Interaction: Controlled by movement scripts. Functionality: Receives path calculation requests from movement scripts and returns results (potentially in a later frame). Attachment: Must be attached to an agent that needs to move, along with a movement script. ``` -------------------------------- ### Setup Method (Vector3, Vector3, OnPathDelegate) Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/floodpathtracer Sets up the path with a start point, end point, and a callback delegate. This method is protected. ```APIDOC Setup( start: Vector3, end: Vector3, callbackDelegate: OnPathDelegate ): void ``` -------------------------------- ### Setup Method (Vector3, FloodPath, OnPathDelegate) Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/floodpathtracer Sets up the path with a start point, a flood path, and a callback delegate. This method is protected. ```APIDOC Setup( start: Vector3, flood: FloodPath, callback: OnPathDelegate ): void ``` -------------------------------- ### Setup Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/xpath Sets up the path with start and end points and a callback delegate. This method is protected. ```APIDOC void Setup ( Vector3 start, Vector3 end, OnPathDelegate callbackDelegate ) ``` -------------------------------- ### C# Example: Registering and Logging Off-Mesh Link Traversal Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/offmeshlinks2 This C# example demonstrates how to implement the IOffMeshLinkHandler and IOffMeshLinkStateMachine interfaces to register a custom handler for off-mesh link traversal. The GetOffMeshLinkStateMachine method logs a message when traversal starts, and the example falls back to the default movement implementation for the actual traversal. ```C# using UnityEngine; using Pathfinding; using Pathfinding.ECS; public class LogOffMeshLinkTraversal : MonoBehaviour, IOffMeshLinkHandler, IOffMeshLinkStateMachine { // Register this class as the handler for off mesh links when the component is enabled. // This component supports registering to both NodeLink2 and FollowerEntity. void OnEnable () { if (TryGetComponent(out var link)) link.onTraverseOffMeshLink = this; if (TryGetComponent(out var ai)) ai.onTraverseOffMeshLink = this; } void OnDisable () { if (TryGetComponent(out var link)) link.onTraverseOffMeshLink = null; if (TryGetComponent(out var ai)) ai.onTraverseOffMeshLink = null; } IOffMeshLinkStateMachine IOffMeshLinkHandler.GetOffMeshLinkStateMachine (AgentOffMeshLinkTraversalContext context) { Debug.Log("An agent started traversing an off-mesh link"); return this; } } ``` -------------------------------- ### A* Pathfinding: Example Meta.json Structure Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/saveloadgraphs Provides an example of the `meta.json` file structure used in A* Pathfinding serialization. This file contains essential metadata like version, graph count, GUIDs, and graph types, crucial for loading other graph data. ```JSON { "version": "3.0.9.5", "graphs": 1, "guids": [ "0d83c93fc4928934-8362a8662ec4fb9d" ], "typeNames": [ "Pathfinding.GridGraph" ] } ``` -------------------------------- ### Example: Queueing and Handling a Path with Seeker.StartPath in C# Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/seeker This C# example demonstrates how to use the Seeker component to queue a path request and handle its completion. It shows how to get the Seeker, call StartPath with start and end points, and define an OnPathComplete callback to process the calculated path, including error handling and drawing the path in the scene view. ```C# 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); } } ``` -------------------------------- ### AstarPath Component Overview Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/getstarted Documentation for the AstarPath component, which manages all graph data in a scene. It follows the singleton pattern and can contain multiple graphs of various types, each managing its own nodes. ```APIDOC AstarPath Component: Purpose: Holds all graph data in a scene. Pattern: Singleton (only one instance per scene). Contents: Can contain one or many graphs (same or different types). Graph Management: Each graph manages its own nodes (potentially millions). ``` -------------------------------- ### Start Method Documentation Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/minebotai Documents the `Start` method, which initiates path searching and should typically call `base.Start()` if overridden. ```APIDOC Start: void Start() Description: Starts searching for paths. If you override this method you should in most cases call base.Start () at the start of it. See: Init Notes: Protected ``` -------------------------------- ### Start Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/aibase Starts searching for paths. If you override this method you should in most cases call base.Start () at the start of it. ```APIDOC Method: Start Access: Protected Return Type: void Parameters: None Description: Starts searching for paths. If you override this method you should in most cases call base.Start () at the start of it. See Also: Init ``` -------------------------------- ### APIDOC: Start Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/graphupdatescene Performs initialization tasks when the component starts. ```APIDOC void Start() ``` -------------------------------- ### void Start Private Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/navmeshprefab Start is called before the first frame update. ```APIDOC void Start () Start is called before the first frame update. ``` -------------------------------- ### void Start Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/localspacerichai Starts searching for paths. If you override this method you should in most cases call base.Start () at the start of it. ```APIDOC void Start () ``` -------------------------------- ### Setup Method (Vector3, Vector3, OnPathDelegate) Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/multitargetpath No description ```APIDOC Protected void Setup( Vector3 start, Vector3 end, OnPathDelegate callbackDelegate ) ``` -------------------------------- ### Setup Method (Vector3, Vector3[], OnPathDelegate[], OnPathDelegate) Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/multitargetpath No description ```APIDOC Protected void Setup( Vector3 start, Vector3[] targets, OnPathDelegate[] callbackDelegates, OnPathDelegate callback ) ``` -------------------------------- ### Start Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/aipathalignedtosurface A protected lifecycle method that starts searching for paths. If overridden, `base.Start()` should typically be called at the beginning. ```APIDOC void Start() ``` -------------------------------- ### C# Example: Constructing and Starting a RandomPath Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/randompath This C# code demonstrates how to create a RandomPath object, set its properties like spread, and initiate the pathfinding process using a Seeker component. It shows how to define the G-score at which the path should terminate and how to handle the path completion with a callback function. ```C# // Call a RandomPath call like this, assumes that a Seeker is attached to the GameObject // The path will be returned when the path is over a specified length (or more accurately when the traversal cost is greater than a specified value). // A score of 1000 is approximately equal to the cost of moving one world unit. int theGScoreToStopAt = 50000; // Create a path object RandomPath path = RandomPath.Construct(transform.position, theGScoreToStopAt); // Determines the variation in path length that is allowed path.spread = 5000; // Get the Seeker component which must be attached to this GameObject Seeker seeker = GetComponent(); // Start the path and return the result to MyCompleteFunction (which is a function you have to define, the name can of course be changed) seeker.StartPath(path, MyCompleteFunction); ``` -------------------------------- ### A* Pathfinding: Loading Graph Data from Unity TextAsset Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/saveloadgraphs Illustrates how to embed A* Pathfinding graph data within a Unity TextAsset for easier build inclusion. The example C# script demonstrates loading this binary data at game start, emphasizing the need for a .bytes extension. ```C# using UnityEngine; using System.Collections; using Pathfinding; public class TestLoader : MonoBehaviour { public TextAsset graphData; // Load the graph when the game starts void Start () { AstarPath.active.data.DeserializeGraphs(graphData.bytes); } } ``` -------------------------------- ### LightweightRVOControlSystem Struct API Reference Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/lightweightrvocontrolsystem API documentation for the `LightweightRVOControlSystem` struct, an example system designed for controlling and rendering RVO agents within the A* Pathfinding Project. This system is intended for the RVO example scene and as a reference, relying on `LightweightRVOMoveSystem` and `RVOSystem`. ```APIDOC Struct LightweightRVOControlSystem Extends ISystem Description: Lightweight example system for controlling and rendering RVO agents. This system is not intended for production use, primarily for the RVO example scene and as a reference. It relies on LightweightRVOMoveSystem and RVOSystem. Inner Types: AlignAgentWithMovementDirectionJob Description: Job to update each agent's position and rotation based on its movement direction. JobControlAgents Description: Job to set the direction each agent wants to move in. Public Methods: OnCreate(state: ref SystemState) : void Description: Public method to initialize the system. OnUpdate(state: ref SystemState) : void Description: Public method to update the system. Public Variables: debug: AgentDebugFlags Description: Determines what kind of debug info the RVO system should render as gizmos. entityQueryControl: EntityQuery entityQueryDirection: EntityQuery ``` -------------------------------- ### Method: AddStartNodesToHeap() Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/constantpath Adds start nodes to the heap. ```APIDOC Protected void AddStartNodesToHeap () ``` -------------------------------- ### Configuring RichAI for Navmesh Movement Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/getstarted2 Details the setup process for the RichAI component, including attaching it to a GameObject, adding a child Capsule for visualization, and important considerations regarding colliders and pivot points for correct ground detection. It also advises on performance for multiple characters. ```Unity Component Setup 1. Create a new GameObject. 2. Attach the RichAI component to it (a Seeker will be automatically attached). 3. For visualization, add a Capsule object as a CHILD object to the root GameObject. 4. Move the Capsule one unit up so the root GameObject's pivot point is at the Capsule's base (RichAI assumes pivot at feet). 5. IMPORTANT: Remove the Capsule Collider (and any other colliders) from the character, OR configure the Gravity -> Raycast Ground Mask field on the RichAI component to exclude those colliders. 6. Note: While CharacterController is supported, it is not recommended for many characters due to performance. ``` -------------------------------- ### WelcomeScreen Class API Reference Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/welcomescreen Detailed API documentation for the WelcomeScreen class, which extends Unity's EditorWindow. It includes public methods for GUI creation and sample management, static methods for instance creation, public variables for state tracking, and private members for internal logic like logo animation, sample import, and documentation links. ```APIDOC Class WelcomeScreen Extends EditorWindow Public Methods: CreateGUI(): void OnEnable(): void OnPostImportedSamples(): void Public Static Methods: Create(): void TryCreate(): void Public Variables: isImportingSamples: bool Private/Protected Members: AnimateLogo(logo: VisualElement): void FirstSceneToLoad: string = "Recast3D" (Static) GetSamples(out sample: UnityEditor.PackageManager.UI.Sample): bool ImportSamples(): void OnAssemblyCompilationFinished(assembly: string, message: CompilerMessage[]): void OpenChangelog(): void OpenDocumentation(): void OpenGetStarted(): void askedAboutQuitting: bool m_VisualTreeAsset: VisualTreeAsset = default ``` -------------------------------- ### Typical Path Pooling Usage in C# Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/pooling This C# example demonstrates how to implement path pooling in an AI script using the A* Pathfinding Project's `Claim` and `Release` methods. It shows a `MonoBehaviour` class that starts a path, claims the new path upon completion, and releases the previous path back to the pool, while also drawing the path in the editor. ```C# public class SomeAI : MonoBehaviour { ABPath path; public IEnumerator Start () { while (true) { GetComponent().StartPath(transform.position, transform.position + transform.forward*10, OnPathComplete); } } void OnPathComplete (Path p) { // Release the previous path back to the pool if (path != null) path.Release(this); path = p as ABPath; // Claim the new path path.Claim(this); } void Update () { // Draw the path in the editor if (path != null && path.vectorPath != null) { for (int i = 0; i < path.vectorPath.Count-1; i++) { Debug.DrawLine(path.vectorPath[i], path.vectorPath[i+1], Color.green); } } } } ``` -------------------------------- ### Configuring GridGraph for A* Pathfinding Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/getstarted Details on adding and configuring a GridGraph, which generates nodes in a grid pattern. This includes setting the Node Size, Position, Width, and Depth variables to ensure the grid accurately covers the walkable area of the scene. ```APIDOC GridGraph Configuration: - Add Graph: "GridGraph" (from Graphs area) - GridGraph Settings: - Node Size: 1 (default) - Position: - Selector: "bottom-left" - Coordinates: (-50, -0.1, -50) - Width: 100 - Depth: 100 ``` -------------------------------- ### Adding A* Pathfinding Component to Unity Scene Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/getstarted Steps to add the AstarPath component to a new GameObject in Unity. This component is the core of the A* Pathfinding System, managing graphs and path calculations. It highlights the importance of the Graphs area and the Scan button. ```APIDOC A* Pathfinding System Integration: - Create new GameObject: "A*" - Add Component: "AstarPath" (Menu bar → Components → Pathfinding → AstarPath) - AstarPath Inspector Overview: - Graphs area: Holds scene graphs (up to 256, typically 1-2) - Scan button: Calculates graph based on settings and world - Shortcut for Scan: Cmd+Alt+S (mac) / Ctrl+Alt+S (windows) ``` -------------------------------- ### WelcomeScreen Class Reference Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/pathfinding Documentation for the WelcomeScreen class. ```APIDOC WelcomeScreen: ``` -------------------------------- ### Wait for Path Calculation with Coroutine Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/constantpath Demonstrates how to use the WaitForPath method with a Unity coroutine to asynchronously wait for a path to be calculated. The example shows how to get the Seeker component, start a path, yield until it's complete, and then draw the resulting path. ```C# IEnumerator Start () { // Get the seeker component attached to this GameObject var seeker = GetComponent(); var path = seeker.StartPath(transform.position, transform.position + Vector3.forward * 10, null); // Wait... This may take a frame or two depending on how complex the path is // The rest of the game will continue to run while we wait yield return StartCoroutine(path.WaitForPath()); // The path is calculated now // Draw the path in the scene view for 10 seconds for (int i = 0; i < path.vectorPath.Count - 1; i++) { Debug.DrawLine(path.vectorPath[i], path.vectorPath[i+1], Color.red, 10); } } ``` -------------------------------- ### Configuring Height Testing for A* GridGraph Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/getstarted Explains how height testing works within the A* system (using raycasting) to place nodes at their correct height. It details how to configure the Mask to ensure rays only hit the 'Ground' layer, preventing nodes from being placed on or through obstacles. ```APIDOC Height Testing Settings: - Functionality: Fires rays from [Ray Length] units above grid downwards; node placed where ray hits. - Unwalkable When No Ground: If true, node is unwalkable if no hit. If false, node placed at Y=0 relative to grid. - Mask: Set to "Ground" layer only (to exclude "Obstacles") ``` -------------------------------- ### C# Example: Asynchronously Wait for Path Calculation Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/randompath Demonstrates how to use `WaitForPath()` to asynchronously wait for a path to be calculated without blocking the main thread. It shows how to get the `Seeker` component, start a path, yield until it's complete, and then draw the resulting path. ```csharp IEnumerator Start () { // Get the seeker component attached to this GameObject var seeker = GetComponent(); var path = seeker.StartPath(transform.position, transform.position + Vector3.forward * 10, null); // Wait... This may take a frame or two depending on how complex the path is // The rest of the game will continue to run while we wait yield return StartCoroutine(path.WaitForPath()); // The path is calculated now // Draw the path in the scene view for 10 seconds for (int i = 0; i < path.vectorPath.Count - 1; i++) { Debug.DrawLine(path.vectorPath[i], path.vectorPath[i+1], Color.red, 10); } } ``` -------------------------------- ### StartPoint Property Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/randompath Start point of the path. ```APIDOC Vector3 startPoint Description: Start point of the path. Details: This is the closest point on the startNode to originalStartPoint. ``` -------------------------------- ### AIBase.Start Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/aipath Starts searching for paths. If you override this method you should in most cases call base.Start() at the start of it. ```APIDOC void Start () ``` -------------------------------- ### Asynchronously Wait for Path Calculation in Unity Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/floodpathtracer Demonstrates how to use the `WaitForPath` method with a Unity Coroutine to asynchronously wait for a path to be calculated by the A* Pathfinding Project. This allows the game to continue running while the pathfinding computation occurs, improving responsiveness. The example shows how to get the Seeker component, start a path, wait for its completion, and then draw the resulting path in the scene view. ```C# IEnumerator Start () { // Get the seeker component attached to this GameObject var seeker = GetComponent(); var path = seeker.StartPath(transform.position, transform.position + Vector3.forward * 10, null); // Wait... This may take a frame or two depending on how complex the path is // The rest of the game will continue to run while we wait yield return StartCoroutine(path.WaitForPath()); // The path is calculated now // Draw the path in the scene view for 10 seconds for (int i = 0; i < path.vectorPath.Count - 1; i++) { Debug.DrawLine(path.vectorPath[i], path.vectorPath[i+1], Color.red, 10); } } ``` -------------------------------- ### SyncDestinationTransformSystem.OnCreate Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/syncdestinationtransformsystem Initializes the system when it is created. This public method takes a reference to a SystemState object. ```APIDOC void OnCreate (ref SystemState state) ``` -------------------------------- ### C# Example: Setting Destination and Waiting for Path/Arrival Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/aipathalignedtosurface Provides two C# coroutine examples demonstrating how to set an AI agent's destination, immediately initiate a path search, and then wait until the agent has either reached the destination or completed its path calculation and reached the end of the path. ```C# 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 } ``` ```C# 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 } ``` -------------------------------- ### APIDOC: AIBase.Init Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/aibase Private method for initialization. ```APIDOC Method: void Init() Description: Private method for initialization. ``` -------------------------------- ### C# Example: Queueing Path with Seeker.StartPath and OnPathComplete Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/seeker This C# example demonstrates how to use the Seeker.StartPath method to request a path calculation from the current GameObject's position to a target. It also shows how to define and use an OnPathComplete method to handle the path calculation results, including error checking and drawing the calculated path in the scene view. ```C# 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); } } ``` -------------------------------- ### StartNode Property Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/randompath Start node of the path. ```APIDOC GraphNode startNode Description: Start node of the path. ``` -------------------------------- ### Get Hierarchical Dirty Offset Constant (int HierarchicalDirtyOffset) Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/graphnode Represents the starting bit position for IsHierarchicalNodeDirty bits. ```APIDOC const int HierarchicalDirtyOffset = 18 Description: Start of IsHierarchicalNodeDirty bits. See: IsHierarchicalNodeDirty ``` -------------------------------- ### Default ITraversalProvider Implementation Example Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/traversal_provider Provides a concrete C# example of how to implement the ITraversalProvider interface, showing the default logic for CanTraverse (node and connection) and GetTraversalCost methods, including considerations for node walkability, tags, and penalties. It also includes the filterDiagonalGridConnections property. ```C# public class MyCustomTraversalProvider : ITraversalProvider { public bool CanTraverse (Path path, GraphNode node) { // Make sure that the node is walkable and that the 'enabledTags' bitmask // includes the node's tag. return node.Walkable && (path.enabledTags >> (int)node.Tag & 0x1) != 0; // alternatively: // return DefaultITraversalProvider.CanTraverse(path, node); } public bool CanTraverse (Path path, GraphNode from, GraphNode to) { return CanTraverse(path, to); } public uint GetTraversalCost (Path path, GraphNode node) { // The traversal cost is the sum of the penalty of the node's tag and the node's penalty return path.GetTagPenalty((int)node.Tag) + node.Penalty; // alternatively: // 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; } } } ``` -------------------------------- ### API Method: AddStartNodesToHeap Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/floodpathtracer Protected method to add start nodes to the heap. ```APIDOC void AddStartNodesToHeap () ``` -------------------------------- ### Get Tag Offset Constant (int FlagsTagOffset) Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/graphnode Represents the starting bit position for tag bits, used internally. ```APIDOC const int FlagsTagOffset = 19 Description: Start of tag bits. See: Tag ``` -------------------------------- ### Prepare Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/floodpathtracer Initializes the path. This method traces the path from the start node. This method is protected. ```APIDOC Prepare(): void ``` -------------------------------- ### Get Hierarchical Index Offset Constant (int FlagsHierarchicalIndexOffset) Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/graphnode Represents the starting bit position for hierarchical node index bits. ```APIDOC const int FlagsHierarchicalIndexOffset = 1 Description: Start of hierarchical node index bits. See: HierarchicalNodeIndex ``` -------------------------------- ### API Reference: Seeker.StartPath Method (Vector3, Vector3, OnPathDelegate) Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/seeker Documentation for the `StartPath` method, which queues a path to be calculated from a start point to an end point. It details the `start`, `end`, and `callback` parameters, and explains that the callback is invoked upon path completion unless the path is canceled. ```APIDOC Path StartPath(Vector3 start, Vector3 end, OnPathDelegate callback) Description: Queue a path to be calculated. The callback will be called when the path has been calculated (which may be several frames into the future). Callback will not be called if the path is canceled (e.g when a new path is requested before the previous one has completed) Parameters: start (Vector3): The start point of the path end (Vector3): The end point of the path callback (OnPathDelegate): The function to call when the path has been calculated. If you don't want a callback (e.g. if you instead poll path.IsDone or use a similar method) you can set this to null. Returns: Path ``` -------------------------------- ### Prepare Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/randompath Prepares the path. Searches for start and end nodes and does some simple checking if a path is at all possible. ```APIDOC void Prepare() ``` -------------------------------- ### PrepareBase Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/path No description provided. This method is `Private`. ```APIDOC PrepareBase(PathHandler handler) : void handler: PathHandler - The path handler. ``` -------------------------------- ### Path.AddStartNodesToHeap Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/path Adds start nodes to the heap during path calculation. ```APIDOC Protected void AddStartNodesToHeap () ``` -------------------------------- ### Get Graph Index Offset Constant (int FlagsGraphOffset) Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/graphnode Represents the starting bit position for graph index bits, used internally. ```APIDOC const int FlagsGraphOffset = 24 Description: Start of graph index bits. See: GraphIndex ``` -------------------------------- ### Seeker.StartPath Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/upgrading Initiates a pathfinding request. In version 5.0+, it's recommended to pass a callback directly to this method instead of relying on `Seeker.pathCallback`. ```APIDOC Seeker.StartPath(start: Vector3, end: Vector3, callback: OnPathDelegate = null) start: The starting position for the path. end: The target position for the path. callback: (Optional) A delegate to be called when the path calculation is complete. ``` -------------------------------- ### Struct Scheduler API Reference Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/scheduler Detailed documentation for the `Scheduler` struct, including its public methods and variables, providing insights into its functionality and how to interact with it programmatically. ```APIDOC Struct Scheduler: Access: Public Methods: Dispose(): Returns: void Access: Public GetEntityQuery(allocator: Allocator): Returns: EntityQueryBuilder Parameters: allocator: Allocator Access: Public ScheduleParallel(systemState: ref SystemState, query: EntityQuery, dependency: JobHandle): Returns: JobHandle Parameters: systemState: ref SystemState query: EntityQuery dependency: JobHandle Access: Public Scheduler(systemState: ref SystemState): Returns: Scheduler Parameters: systemState: ref SystemState Access: Public Update(systemState: ref SystemState): Returns: void Parameters: systemState: ref SystemState Access: Public Variables: AgentCylinderShapeTypeHandleRO: ComponentTypeHandle Access: Public AgentMovementPlaneTypeHandleRO: ComponentTypeHandle Access: Public DestinationPointTypeHandleRO: ComponentTypeHandle Access: Public LocalTransformTypeHandleRO: ComponentTypeHandle Access: Public ManagedStateTypeHandleRW: ComponentTypeHandle Access: Public MovementSettingsTypeHandleRO: ComponentTypeHandle Access: Public MovementStateTypeHandleRW: ComponentTypeHandle Access: Public ReadyToTraverseOffMeshLinkTypeHandleRW: ComponentTypeHandle Access: Public entityManagerHandle: GCHandle Access: Public onlyApplyPendingPaths: bool Access: Public ``` -------------------------------- ### Prepare Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/floodpath Called before the path calculation is started, specifically right before Initialize. ```APIDOC void Prepare () ``` -------------------------------- ### Implement IOffMeshLinkHandler for Custom Link Traversal Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/nodelink2 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 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. ```C# using UnityEngine; using Pathfinding; using System.Collections; using Pathfinding.ECS; 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().onTraverseOffMeshLink = this; void OnDisable() => GetComponent().onTraverseOffMeshLink = null; IOffMeshLinkStateMachine IOffMeshLinkHandler.GetOffMeshLinkStateMachine(AgentOffMeshLinkTraversalContext context) => this; void IOffMeshLinkStateMachine.OnFinishTraversingOffMeshLink (AgentOffMeshLinkTraversalContext context) { Debug.Log("An agent finished traversing an off-mesh link"); } void IOffMeshLinkStateMachine.OnAbortTraversingOffMeshLink () { Debug.Log("An agent aborted traversing an off-mesh link"); } IEnumerable IOffMeshLinkStateMachine.OnTraverseOffMeshLink (AgentOffMeshLinkTraversalContext ctx) { var start = (Vector3)ctx.link.relativeStart; var end = (Vector3)ctx.link.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; } } } } ``` -------------------------------- ### Path Property: endPointKnownBeforeCalculation (bool) Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/abpath True if this path type has a well defined end point, even before calculation starts. This is for example true for the ABPath type, but false for the RandomPath type. ```APIDOC bool endPointKnownBeforeCalculation ``` -------------------------------- ### Path Method: AddStartNodesToHeap Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/euclideanembeddingsearchpath Protected method to add start nodes to the heap. No further description provided. ```C# void AddStartNodesToHeap () ``` -------------------------------- ### Getting All Reachable Nodes from a Given Node (C#) Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/usingnodes The `PathUtilities.GetReachableNodes` method returns a list of all `GraphNode` instances that can be reached from a specified starting node. This is useful for exploring connected areas of the graph. ```C# List reachableNodes = PathUtilities.GetReachableNodes(node); ``` -------------------------------- ### C# StackPool Usage Example Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/stackpool Demonstrates how to claim and release a stack using the `StackPool` class. It highlights the basic workflow for utilizing the pool. ```C# Stack foo = StackPool.Claim (); // Use it and do stuff with it StackPool.Release (foo); ``` -------------------------------- ### Setting Up AIDestinationSetter for Target Following Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/getstarted2 Explains how to attach the AIDestinationSetter component to the same GameObject as RichAI and link it to a 'Target' Transform, enabling the AI agent to follow a specified object. ```Unity Component Setup 1. Attach the AIDestinationSetter component to the same GameObject as the RichAI component. 2. Create another GameObject named "Target". 3. Assign the "Target" GameObject to the 'Target' field on the AIDestinationSetter component. ``` -------------------------------- ### BlockUntilCalculated Method Usage Example Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/path Demonstrates how to start a path calculation using a Seeker and then immediately block the execution until the path is fully calculated and its callback has been invoked. This ensures the path data is available synchronously. ```C# var path = seeker.StartPath(transform.position, transform.position + Vector3.forward * 10, OnPathComplete); path.BlockUntilCalculated(); // The path is calculated now, and the OnPathComplete callback has been called ``` -------------------------------- ### Example: RemovePartialConnection Usage Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/linknode Demonstrates how to use `RemovePartialConnection` within an AstarWorkItem to disconnect two nodes after establishing a connection. It shows how to get nearest nodes, calculate cost, add partial connections, check for outgoing connections, and then remove them. ```C# [AstarPath].active.AddWorkItem(new AstarWorkItem(ctx => { // 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; node1.AddPartialConnection(node2, cost, true, true); node2.AddPartialConnection(node1, cost, true, true); node1.ContainsOutgoingConnection(node2); // True node1.RemovePartialConnection(node2); node2.RemovePartialConnection(node1); })); ``` -------------------------------- ### C#: Custom MovementUpdate Usage Example Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/localspacerichai Illustrates how to manually control agent movement by disabling `canMove`, calling `MovementUpdate` to get desired movement, modifying it, and then applying it with `FinalizeMovement`. This replicates the component's normal behavior but allows for custom modifications. ```C# 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); } ``` -------------------------------- ### EuclideanEmbeddingSearchPath.Construct Static Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/euclideanembeddingsearchpath Static method to construct a new `EuclideanEmbeddingSearchPath` instance with specified costs, stride, pivot, and start node. ```APIDOC EuclideanEmbeddingSearchPath Construct( UnsafeSpan costs, uint costIndexStride, uint pivotIndex, GraphNode startNode ) ``` -------------------------------- ### API: float rotationSpeed Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/pidmovement Specifies the desired rotation speed in degrees per second. If the agent is in an open area and gets a new destination directly behind itself, it will start to rotate with exactly this speed. The agent will slow down its rotation speed as it approaches its desired facing direction. ```APIDOC float rotationSpeed ``` -------------------------------- ### UseSettings Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/randompath Copies the given settings into this path. ```APIDOC void UseSettings ( PathRequestSettings settings ) ``` -------------------------------- ### CalculatePathRequestEndpoints Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/richai Outputs the start point and end point of the next automatic path request. This is a separate method to make it easy for subclasses to swap out the endpoints of path requests. For example the [LocalSpaceRichAI](localspacerichai.html) script which requires the endpoints to be transformed to graph space first. ```APIDOC void CalculatePathRequestEndpoints ( out [Vector3] start, out [Vector3] end ) ``` -------------------------------- ### Prepare Method for Path Initialization Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/path Called before the path is started. This method is `Protected` and `Abstract`. Called right before Initialize. ```APIDOC IPathInternals.Prepare() : void Prepare() : void ``` -------------------------------- ### C# Example: Waiting for AI to Reach Destination Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/iastarai This C# code demonstrates how to use the "reachedDestination" property to pause execution until an AI agent has successfully arrived at its target. It initializes the AI's destination, starts a path search, and then yields control until the destination is reached. ```C# 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 } ``` -------------------------------- ### Int3 Property: Get Vector Magnitude Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/int3 Returns the magnitude (length) of the vector from 0,0,0 to this point. This property is useful for distance calculations. For example, Debug.Log ("Distance between 3,4,5 and 6,7,8 is: "+(new Int3(3,4,5) - new Int3(6,7,8)).magnitude); demonstrates its use. ```APIDOC float magnitude ``` -------------------------------- ### Request and Visualize Path in Unity Editor (C#) Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/editormode Once the AstarPath system is initialized and graphs are scanned, paths can be requested synchronously in editor mode. This example constructs an ABPath, starts the pathfinding process, logs the path details, and then draws the calculated path in the scene view for visual debugging. ```C# ABPath path = ABPath.Construct(transform.position, target.position); AstarPath.StartPath(path); // Everything is synchronous so the path is calculated now Debug.Log("Found a path with " + path.vectorPath.Count + " points. The error log says: " + path.errorLog); // Draw the path in the scene view for (int i = 0; i < path.vectorPath.Count - 1; i++) { Debug.DrawLine(path.vectorPath[i], path.vectorPath[i+1], Color.red); } ``` -------------------------------- ### PrepareBase API Documentation Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/euclideanembeddingsearchpath Prepares low-level path variables necessary for the calculation. This method is always called before Prepare, Initialize, and CalculateStep functions, setting up the environment for the path search. ```APIDOC PrepareBase(pathHandler: PathHandler): void pathHandler: The PathHandler instance responsible for managing path calculations. ``` -------------------------------- ### APIDOC: AIBase.CalculatePathRequestEndpoints Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/aibase Outputs the start point and end point of the next automatic path request. This is a separate method to make it easy for subclasses to swap out the endpoints of path requests. For example the LocalSpaceRichAI script which requires the endpoints to be transformed to graph space first. ```APIDOC Method: void CalculatePathRequestEndpoints(out Vector3 start, out Vector3 end) Description: Outputs the start point and end point of the next automatic path request. Parameters: start: out Vector3 end: out Vector3 ``` -------------------------------- ### Start Method Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/ailerp Initiates the process of searching for paths. This is a protected method, and if overridden, it is generally recommended to call `base.Start()` at the beginning of the override. ```APIDOC void Start () ``` -------------------------------- ### Unity AstarAI Script for Path Request Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/custom_movement_script This C# script demonstrates how to initiate a pathfinding request using the A* Pathfinding Project's `Seeker` component in Unity. It defines an `AstarAI` MonoBehaviour that gets a reference to the `Seeker`, starts a path from the current position to a target, and logs the result upon path completion. ```C# using UnityEngine; using System.Collections; // Note this line, if it is left out, the script won't know that the class 'Path' exists and it will throw compiler errors // This line should always be present at the top of scripts which use pathfinding using Pathfinding; public class AstarAI : MonoBehaviour { public Transform targetPosition; public void Start () { // Get a reference to the Seeker component we added earlier Seeker seeker = GetComponent(); // Start to calculate a new path to the targetPosition object, return the result to the OnPathComplete method. // Path requests are asynchronous, so when the OnPathComplete method is called depends on how long it // takes to calculate the path. Usually it is called the next frame. seeker.StartPath(transform.position, targetPosition.position, OnPathComplete); } public void OnPathComplete (Path p) { Debug.Log("Yay, we got a path back. Did it have an error? " + p.error); } } ``` -------------------------------- ### A* Pathfinding: Example Grid Graph Settings JSON Source: https://arongranberg.com/astar/documentation/5_1_1_0e39bc772/classes.html/saveloadgraphs Shows a partial JSON structure for `graph#.json` files, specifically illustrating serialized settings for a grid graph within the A* Pathfinding Project. This includes various configuration parameters like size, rotation, and node properties. ```JSON { "aspectRatio":1, "rotation":{ "x":0, "y":0, "z":0 }, "center":{ "x":0, "y":-0.1, "z":0 }, "unclampedSize":{ "x":100, "y":100 }, "nodeSize":1, "maxClimb":0.4, "maxClimbAxis":1, "maxSlope":90, "erodeIterations":0, "autoLinkGrids":false, "autoLinkDistLimit":10, "neighbours":"Eight", "cutCorners":true, "penaltyPositionOffset":0, "penaltyPosition":false, "penaltyPositionFactor":1, "penaltyAngle":false, "penaltyAngleFactor":100, "open":true, "infoScreenOpen":false ... } ```