GetPathLength Function Structure Feedback

Hello, I wanted to get a bit of feedback on how I decided to write the GetPathLength function:

       private float GetPathLength(NavMeshPath path)
       {
            float pathLength = 0;
            Vector3 lastCorner = transform.position;

            foreach(Vector3 corner in path.corners)
            {
                pathLength += Vector3.Distance(lastCorner, corner);
                lastCorner = corner;
            }

            return pathLength;
        }

Is there anything wrong with this approach that I might not be seeing? I’m starting with the distance calculation between the Player and the first corner, then each additional corner from there. Of course it compiles and runs just fine, but I’m wondering why it was decided to use a FOR loop instead of a FOREACH against the corners array.

Is there no potential for path.corners to only have 1 corner which could have a calculated distance between the corner and the Player that is greater than the maxPathLength? In that case wouldn’t we miss that if we were to simply return 0 with that first IF statement?

Thank you in advance for your input!

This should be just fine. Either a for or a foreach loop works in this case.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms