Getting random values out of while loop for unknown reason

Im trying to have a path only have a max distance regardless of where the initial destination is. to do this I’m attempting to use Vector3.lerp in a while loop. it appears to work sometimes but other times is giving seemingly random values and I cant figure out why.

Code:

{

private NavMeshAgent myAgent;
private NavMeshPath path;

[SerializeField] LineRenderer line;

float pathDistance;

Vector3 FinalPos;
Vector3 p2;
Vector3 p1;

[SerializeField] float moveSpeed;

// Start is called before the first frame update
void Start()
{
    myAgent = GetComponent<NavMeshAgent>();
    
}

// Update is called once per frame
void Update()
{
    Movement();

}

void Movement()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray myRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(myRay, out hit, 100f, whatCanClick))
        {
            float a = 0.9f;
            myAgent.isStopped = true;
            myAgent.SetDestination(hit.point);
            pathDistance = CalculatePathLenth();

            while(pathDistance > moveSpeed)
            {
                
                FinalPos = Vector3.Lerp(p1, p2, a);
                a -= 0.001f;
                myAgent.SetDestination(FinalPos);
                pathDistance = CalculatePathLenth();

                if (a < 0.001f) break;

            }
            print(pathDistance);
            
            a = 0.999f;

            line.positionCount = myAgent.path.corners.Length;
            line.SetPositions(myAgent.path.corners);
            line.enabled = true;
            
            

        }
    }

}

float CalculatePathLenth()
{
    float distance = 0f;

    for (int i = 0; i < myAgent.path.corners.Length - 1; i++)
    {
         p1 = myAgent.path.corners*;*

p2 = myAgent.path.corners[i + 1];
distance += Vector3.Distance(p1, p2);
}
return (distance);
}
}

If myAgent.path.corners.Length is less than 2, p1 and p2 would be undefined. I’m not sure that is the problem, but maybe you could input the max distance in CalculatePathLenth() and skip your while loop and let the function set FinalPos.

float CalculatePathLenth(float max) //sets FinalPos
{
    float distance = 0f;
    //FinalPos = startpos; //maybe you need this?
    for (int i = 0; i < myAgent.path.corners.Length - 1; i++)
    {
        p1 = myAgent.path.corners*;*

p2 = myAgent.path.corners[i + 1];
float segmentlength = Vector3.Distance(p1, p2);
if(distance+segmentlength>max)
{
float into = ((max-distance)/segmentlength); //0…1 into the current seg
FinalPos = Vector3.Lerp(p1, p2, into);
return max;
}
distance += segmentlength;
//FinalPos = p2; //maybe you need this?
}
return (distance);
}