Yield not working properly

I’m working on a pathfinding/waypoints script. I move from waypoint to waypoint with a loop, that does a linear interpolation and yields every frame. This works perfectly, until I reach the first waypoint. After that, it will execute the whole loop without yielding - or at least, that’s what I’ve observed through debugging.

void Update() 
{
	currentPosition = transform.position;
	targetPosition = waypoints[currentWaypoint].waypoint.position;	
	
	StartCoroutine(GetNextPos());
	
	if (currentPosition == targetPosition)
	{
		currentWaypoint = Mathf.Clamp(currentWaypoint + 1, 0, waypoints.Length - 1);
		startPosition = currentPosition;
		targetPosition = waypoints[currentWaypoint].waypoint.position;
	}
}

IEnumerator GetNextPos()
{
	float x = 0f;
	while (x <= 1.0f)
	{
		x += Time.deltaTime * speed;
		transform.position = Vector3.Lerp(startPosition, targetPosition, x);
		yield return null;
	}
}

It is really a bad idea to call StartCoroutine inside Update() without proper control. Each frame you will start a new coroutine which is not what you want. Because after 50 frames you will have 50 coroutines that are executed concurrently.

I don’t know exactly what you want to do, but consider this kind of solution instead that use the Start() method which here is also a coroutine:

IEnumerator Start()
{
    while (aCondition)
    {
        yield return StartCoroutine(GetNextPos());

        aCondition = (some test and value check);
    }
}

IEnumerator GetNextPos()
{
    // your code here

    // populate some member variable to help decide when to start this coroutine again
}

edit: in your case aCondition will be to check whether you reached the last waypoint. And between two calls to GetNextPos(), you can set the start/end values, the same way you do inside the if statement in your Update() method.