How do I use my code with the A* script?

First you need to place one instance of the AstarPath.cs script in your scene, this component will do all the computing.
Then on the object you want to find the path for (your player, enemy or similar), attach the Seeker script and your movement script.

Important : If you want to use Javascript to send pathfinding calls, you need to place the ‘Pathfinding’ folder inside the Standard Assets Folder, you don’t need to do this if you only want to receive completed paths

In your movement script, add this when you want to find the path, for example when the player clicks on a spot on the ground in a RTS game.

C#
(GetComponent (typeof(Seeker)) as Seeker).StartPath ( startPoint, endPoint);
Javascript
GetComponent (Seeker).StartPath ( startPoint, endPoint);
The function does not return anything, so how do we know where to go?
The script will process the request and send the completed path back as fast as it can.
To get the completed path, add this function to your code:

C#
public void PathComplete (Vector3[] points) {
//The points are all the waypoints you need to follow to get to the target
}

Javascript
function PathComplete (points : Vector3[]) {
//The points are all the waypoints you need to follow to get to the target
}

Then it is just for your enemy/droid/whatever to follow the points, an example of this can be seen in the AIFollow script in the example project.

Other messages sent by the Seeker script

If you want to know when the pathfinding returned an error, you have to set the On Error variable in the Seeker component to Error Message and add this function to your code:

C#
public void PathError () {
Debug.Log ("Oh no, the pathfinding returned an error!!");
}

Or you can set On Error to Empty Array and the script will send a PathComplete message but with an empty array.

If you have any questions please post them as a comment or mail me at aron[dot]g[at]me[dot]com

75 Responses to How do I use my code with the A* script?

  1. AlbertoZ says:

    Jason,

    You are amazing, thanks for this java translate!

  2. Lucas says:

    Hey ho..!

    First of all, thanks for the effort that you have put in building and mantaining this code, the world needs more people like you! :D

    Now,

    I’m trying to implement your code into my (first) game.
    I got the tutorial version to work without problems, but now i’m trying to tweak it: I’m dealing with a “naval simulator”, with floating buoyant objects. For this reason i can’t have a plane with a collider, because this would ruin the buoyancy effect of the vessels.

    My problem here is that if i remove the collider from the plane, my “player” object just falls through my “water layer”.

    I believe that the problem could be in the fact that the tutorial script requires the usage of a character controller, that will just fall if not obstructed..

    I tried to add a script that forces the position.y of the object at 0 at every Update cycle, but this got the whole thing messed up, and even if the pathfinding seems to be calculated, the player simply won’t move.

    Any idea about how could i use your script, without relying on a character controller?

    Thanks in advance..!

  3. Lucas says:

    Ha! Ignore the previous mex man, I got it to work..!

    I just used Physics.IgnoreCollision, and it works as a charm! :D

    Thanks for the great script!

  4. stefan embleton says:

    I have come across a strange problem. I set up a terrain navmesh and i have a robot running thru 4 way points and when it reaches each one it calls PathComplete then picks the next waypoint from an array until all waypoints have been reached. My first attempts worked fine. Then on one attempt i got an error from StartPath… nullreference on line 599 of AstarPath. once that error has shown up the project never works again no matter what i do..restart the whole machine same result. Then i discovered that if i do a build then run the project again it works fine, sort of, PathComplete never gets called now. All my code is in Javascript. Im running Unity 2.6 on an iMac Quad. Plenty of power , plenty of RAM… please free to use my email if you want to discuss this… A* shows a lot of potential and i would love to help debug this.

  5. Arno says:

    I love the a* pathfinding. It does wat it say it does. (i only get errors with angry ants)
    I’am a newbie and i just don’t know where to start, so i hope you would give some more info.
    I want a character (not my player) to move from one waypoint to another waypoint.
    So i made a character setup the A*, applied the seeker and the AIfollow.
    But i dont know where to start to make a script to follow from waypoint to waypoint.

    Would you please help….

    I think there are more people out there who want to know this…

  6. Admin says:

    Hi Arno

    if you want an example script you can take a look at the Clicker.cs script which is in the example project.
    But in a nutshell, the only code you need is (C#):
    public Transform myFirstWaypoint;
    public Transform mySecondWaypoint;
    public void Start () {
    (GetComponent (typeof(Seeker)) as Seeker).StartPath (myFirstWaypoint.position, mySecondWaypoint.position);
    }

    This will instruct the character to move from myFirstWaypoint to mySecondWaypoint (works best if the character is already at the first waypoint).
    The code assumes that it is in a script attached to the character.

    The syntax for the calls can be found on the page you have commented on, but you have probably read those already.

  7. Colin says:

    Man! Just found your website today! You are a life saver! This is amazing!

    But, I was wondering how I would implement this into a game like your Massive demo level.

    I want to use a texture map to make sure the seekers don’t go on places they shouldn’t, but I don’t know how to make them run to the 1st seeker they see and have the two engage in a believable fight.

    I have the fight code working but how would I make the seekers move from the opposite ends of the map without making their maxViewingDistance incredibly high?

  8. Admin says:

    I have the fight code working but how would I make the seekers move from the opposite ends of the map without making their maxViewingDistance incredibly high?
    I don’t really understand you question, could you please specify it a bit more?

    Sorry for answering late, I have been (and am) on holiday, but I’m home for one day so I will try to answer as many comments as possible.

  9. Oleg says:

    How can i recalculate grid after adding some buildings during the game?

  10. Admin says:

    HI Oleg

    The best way is to call the (so far undocumented) function called SetNodes.
    You can find an example in the Clicker.cs script.
    Basically you first instantiate the building, then you call
    SetNodes (false,myBuilding.colldider.bounds,true);// (walkable, Bounds, fullPhysicsCheck)
    I think that’s the syntax anyway…don’t remember… check the Clicker.cs script.
    If you use fullPhysicsCheck then it will look exactly as if the building was there since the beginning.
    if you don’t use fullPhysicsCheck the script will just use some approximations instead of the real world data.

  11. Lee says:

    Hi Dude, great work :) This is exactly what I was looking for.

    However I’m having a major problem trying to sort this out. At the moment my objects are following a target around using your AIFollow Script with a modification:

    public Transform myFirstWaypointXX;
    public Transform mySecondWaypointXX;
    private CharacterController controller;
    private AIAnimation animator;
    private Seeker seeker;

    // Make sure there is always a character controller

    public enum Command {
    Stay,
    Walk,
    }

    public IEnumerator Start () {
    (GetComponent (typeof(Seeker)) as Seeker).StartPath (myFirstWaypointXX.position, mySecondWaypointXX.position);
    }
    ——————–

    The basic problem I’m having is that during Run time I want to switch the Target (mySecondWaypointXX)object to a different Object in the scene, but everything I have tried has failed! It seems so simple and yet I’m having no joy!

    At the moment the only way I can change my target is by selecting a different object in the drop-down list before I run the game which although works, it is ultimately useless as I need to be able to do this in Run time :(

  12. Em says:

    thanks for all your work on this Aron!

    Is there a way to avoid automatic generation and just manually define a set of nodes and edges?

    I tried using the “List” mode but it seems to default to a grid.

    I am working on a non-standard game using A* and I like the tools for setting up the graphs but I dont need a lot of the additional features, just basic path of nodes that I define.

    thanks!

  13. Sten says:

    Hi,

    Thanks for sharing this!
    But I have one problem: every time I place/instantiate an object on the terrain i want to recalculate the nodes. I’ve placed the object in the “walls” layer, it has a collider and i’m calling: gameObject.Find(“A*”).GetComponent(“AstarPath”).SetNodes (false,building1.collider.bounds,true);
    What am I doing wrong?

  14. Sten says:

    The problem is that it’s not recalculating the nodes, they are still the same…

  15. Blaze Sanecki says:

    Hello,
    I’m wondering how to make the player walk as close as possible to the non walkable area where target is set. Is there any way to do that? (let’s say I click on the obstacle. I want the player to walk to the edge of the walkable area nearest to the target position)

    Any kind of help with that is appriciated :)

  16. Admin says:

    Sorry for answering late, I have been on holiday without internet.

    Is the goal to have your script recalculate the path in regular intervals (the Start function)?
    If so I can see the problem, your Start function is a IEnumerator function which is good, but you need to add some code to make it repeat, otherwise it will only calculate the path at startup.


    public IEnumerator Start () {
    while (true) {
    (GetComponent (typeof(Seeker)) as Seeker).StartPath (myFirstWaypointXX.position, mySecondWaypointXX.position);
    yield return new WaitForSeconds (0.5F);
    }
    }

    This will make it recalculate the path every 0.5 seconds.

    Better though is to only recalculate the path when you change the target:

    public Transform myFirstTarget;
    public Transform mySecondTarget;
    public Transform myCurrentTarget;

    public void OnGUI () {
    if (GUILayout.Button ("Change Target")) {
    if (myCurrentTarget == myFirstTarget) {
    myCurrentTarget = mySecondTarget;
    } else {
    myCurrentTarget == myFirstTarget;
    }
    RecalculateTarget ();
    }
    }

    public void Start () {
    myCurrentTarget = myFirstTarget;
    RecalculateTarget ();
    }

    public void RecalculateTarget () {
    (GetComponent (typeof(Seeker)) as Seeker).StartPath (transform.position,myCurrentTarget.position);
    }

    This will recalculate the path only when the target is changed.
    Hope this will work,
    Aron

  17. Admin says:

    Hi Em

    Sorry for answering late, I have been on holiday without internet.

    There is no built in generator for defining nodes & edges.
    You can however code a completely custom generator.
    Take a look at the Procedural scene in the example project, that will get you started (sorry no tutorial yet).

  18. Admin says:

    Hi Sten

    Sorry for answering late, I have been on holiday without internet

    Make sure that you are calling set nodes after you instantiate the building otherwise the script will not find it.
    And make sure that it is working if you have it in the scene from the beginning.
    And check if the collider is a trigger, if it is, switch it back to a collider.
    Otherwise I don’t know what the problem is.

  19. Admin says:

    Hi Blaze

    This is a problem I have been struggling with for a time, I have created a solution for it in my test project, unfortunately it will make the game freeze for a split second when the nearest walkable area is far from the target position.
    I think that the 2.8beta version includes logic for getting the nearest node but restricted to a 5 node radius or something (it is possible that it never left my test project though).
    The ultimate solution would include space portioning such as KD-trees, I’m reading up on them right now.

  20. Atty says:

    I`m sorry for not explaining my question, I am new in Unity3D and I want to learn, so here is my detailed question: I have a FPS game in which I have a player and an enemy. The player is controlled by me using the default controller script, and what should I do with my enemy so that it would find my player? First of all I understood that I have to add the AStarPath.cs script to my scene, than I have to add the seeker to my enemy? but do I have to modify anything in the seeker script? so that it would be for a FPS? the other question: how do I make the connection between the enemy`s controller and the seeker? and the 3rd question is where do I add the clicker? to the camera from my player and what do I modify in the clicker script?

    I know that those are many questions, but I hope that you could help me.

    Thank you

  21. Admin says:

    Hi Atty

    Thanks for explaining a bit more.
    The page I linked to before will give you info about how to find the path from point A to B from scripts.
    Here’s how you get the enemy to follow your player: You use exactly the same scripts (AIFollow and Seeker) attached to the enemy but for the enemy you can set the player GameObject to the variable slot named “Target” on the AIFollow component, then you enable the “Continuous Target Search” variable, at startup your enemy will then follow your player. You don’t need to use the Clicker script anywhere, that’s only used for example purposes.
    I can’t help you with the rest in a fps game though (how the enemy should interact with the player when it has found him for example), for those questions the forum is better.
    Pathfinding is quite complicated, so if you are new to Unity, don’t be afraid to ask questions (regarding the pathfinding) here.

    -Aron

  22. Atty says:

    Okay..I`ve done what you`ve told me I`ve added the seeker and AIFollow script to the enemy, in the AIFollow script I gave as target the player, and I`ve added an empty object in which I`ve putted the AStarPath.cs. The thing is that the enemy is not looking for my player. And there is another problem .. when I add the AStarPath.cs script to the empty object it doesn`t appear in a menu type like in your examples. Why is that? and where do I put the code to link the object A to object B (GetComponent (typeof(Seeker)) as Seeker).StartPath ( startPoint, endPoint); in the seeker? and where more exactly?

    Thank you

  23. Atty says:

    Hi Aron,

    Finally I`ve managed to add the AStarPath.cs script, it appeared that menu but the enemy is not moving towards my player, it`s standing still, I`ve scanned for path corectly, Ive added everything you told me except the (GetComponent (typeof(Seeker)) as Seeker).StartPath ( startPoint, endPoint); which I don`t know where to put and how..Can you help me please?

  24. Atty says:

    I`ve done it, my enemy can find my player anywhere:)). Thanks a lot!

  25. Sten says:

    Ok thanks, It’s more or less working now ;)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>