Search Unity

Question How to loop through all objects

Discussion in 'Navigation' started by Rachan, May 14, 2022.

  1. Rachan

    Rachan

    Joined:
    Dec 3, 2012
    Posts:
    782
    Hi there

    this is a flowchart concept



    and I want to know how to find the way to go
    from A > H
    the way should be A > B > D > E > F > G > H

    But actually I still don't know how to do it...
    the simply way should be create the path through all objects
    and all objects has a connector such as
    A connect with (B) and B connect with (A , C , D) something like this...

    so I would like to find the way how to loop through all object
    with some algorithm?

    anyone have some idea?
    and here this is example scene
    https://www.hardworkerstudio.com/Download/nodeSample.rar

    Thanks!!!
     
    Last edited: May 14, 2022
  2. SOICGeek

    SOICGeek

    Joined:
    Jun 25, 2019
    Posts:
    78
    It sounds like you're trying to do pathfinding. If that's the case, you want either A-star (faster) or Dijkstra's algorithm (more correct). Most games go with A-star because it's faster and it gives a good enough result. To connect them, I would just write a component that simply holds references to other nodes. Something like:
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class PathNode : MonoBehaviour {
    4.  
    5.     [SerializeField]
    6.     private PathNode [] _destNodes;
    7.  
    8.     public PathNode [] destNodes {
    9.         get {
    10.             return _destNodes;
    11.         }
    12.     }
    13.  
    14. }
    Drop that on each node that you want to include in the pathfinding. Then to create a path from that to another node, drop the destination node in the inspector on destNodes. Access that from your code something like this:
    Code (CSharp):
    1.  
    2. PathNode currentPosition = startNode.GetComponent<PathNode>();
    3. currentPosition = currentPosition.destNodes[2];
    4. // or whichever one you want to go to.  you should probably use a variable here.
    5. // and don't forget to check to make sure the index isn't less than zero or
    6. // greater than the number of nodes.
    7.  
    If you use a property like that, you won't accidentally change the structure at run-time. If you want to be able to change it at runtime, just make _destNodes public or add a setter in the property.

    Note: Beware of bugs in the above code - I have only proved it correct, not actually tried it. (With apologies to Don Knuth)