Search Unity

Pathfinding in an array/list

Discussion in 'Scripting' started by RoMax92, Sep 12, 2017.

  1. RoMax92

    RoMax92

    Joined:
    May 29, 2017
    Posts:
    135
    Hi, i'm searching a way to do a pathfinding in an array/list of objects with some connections:
    I have these:

    Code (CSharp):
    1. [System.Serializable]
    2. public class Room {
    3.     public string id;
    4.     public Vector3 position;
    5.     public string[] nears; //stanze vicine
    6. }
    Where the nears array is other rooms id,
    and i have already done this to verify the if the start and finish exist:

    Code (CSharp):
    1.  
    2. public List<Room> roomPositions;
    3. private string roomStart = "Room 10";
    4. private string roomFinish = "Room 23";
    5.  
    6. void RoomPathFinder (string roomStart, string roomFinish)
    7.  
    8.     {
    9.         //find the starter//
    10.         int starter = 0;
    11.         for ( int i = 0; i < roomPositions.Count; i++ )
    12.         {
    13.             if ( roomPositions [i].id == roomStart )
    14.             {
    15.                 starter = i;
    16.                 break;
    17.             }
    18.             if (i == roomPositions.Count - 1)
    19.             {
    20.                 Debug.LogWarning ("The start doesn'w exist");
    21.                 return;
    22.             }
    23.         }
    24.  
    25.         //find the finish//
    26.         for ( int i = 0; i < roomPositions.Count; i++ )
    27.         {
    28.             if ( roomPositions [i].id == roomFinish )
    29.             {
    30.                 break;
    31.             }
    32.             if (i == roomPositions.Count - 1)
    33.             {
    34.                 Debug.LogWarning ("The finish doesn'w exist");
    35.                 return;
    36.             }
    37.         }
    38.  
    39.         //to do some path finding
    40.  
    41. }
    My question is: how can i find the path in an array of this tipe?
    If the connection is backward in the array or if the connection is not direct, how can i find the path?
    And how can i know if there are more ways, maybe with less connections?

    Thanks for your help
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    You use a pathfinding algorithm. The most popular is astar. There's a tutorial here:


    It doesn't matter if it's a grid, or objects. You just measure the distance to the destination of each neighbor and eventually find the shortest path.
     
    RoMax92 likes this.