- Home /
 
 
               Question by 
               Bokaii · Oct 26, 2014 at 09:05 PM · 
                multiplayerfpspathfindingonline  
              
 
              Closest array element
Why is this not working? I am trying to find the closest child.
     public GameObject test;
     public Transform[] nodes;
 
     public GameObject closest;
 
     
     // Update is called once per frame
     void Update () {
         nodes = test.GetComponentsInChildren<Transform>();
         nodes [0] = nodes [nodes.Length - 1];
 
 
         float dist = Vector3.Distance (transform.position, nodes[0].position);
 
         for(int i=0;i<nodes.Length;i++){
             float curDist = Vector3.Distance(transform.position, nodes[i].position);
             if(curDist < dist){
                 closest = nodes[i].gameObject;
             }
         }
     }
 
              
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by robertbu · Oct 26, 2014 at 09:12 PM
You need to update 'dist' as well as 'closest':
        if(curDist < dist){
              closest = nodes[i].gameObject;
              dist = curdist;
          }
 
               As the for loop can start at 1 rather than 0.
Thank you so much! I completely derped out! :P I forgot all about the dist! THAN$$anonymous$$ YOU! :D
Your answer
 
             Follow this Question
Related Questions
Find closest object with tag 1 Answer
Find children of object and store in an array 3 Answers
Remove first element of array 1 Answer
Find closest transform 1 Answer
Add one on local z axis 3 Answers