Coroutine randomly stops and continues after pausing and unpausing game

I have a path fallowing script and this is the coroutine that is called when a path has been generated (before calling it stops it as well). The problem is when enemy (the one with this coroutine) is going through one of the many paths and randomly decides to stop. Only way to get it unstuck is with pausing the game and unpausing (Ctrl+Shift+P) then it runs a bit and the stops again. All of the lines of code are fired when it’s stuck. However, what I have noticed is that the last line that tells enemy object to move doesn’t work even thought it is fired. I didn’t have this problem before while working on this project for a half a year. This is the Code for courotine:

IEnumerator FallowPath()
    {
        
        if (path.Length <1)
        {
            StopCoroutine("FallowPath");
        }
        else {
            Vector2 currentWaypoint = path[0];

            targetIndex = 0;

            while (true)
            {
                if (transform.position.Equals(currentWaypoint))
                {
                    targetIndex++;

                    if (targetIndex >= path.Length)
                    {
                        yield break;
                    }

                    currentWaypoint = path[targetIndex];
                }

                transform.position = Vector2.MoveTowards(transform.position, currentWaypoint, speed * Time.deltaTime);
                
                yield return null;
            }
        }
    }

Well a common issue with such a setup is that you possibly have two or more coroutines running at the same time which are fighting each other since they work on the same object. Note that you should never use StopCoroutine with a string argument. This only works for coroutines started with a string name. If you just want to stop the current coroutine either use yield break or just let it reach the end of the method which will naturally terminate the coroutine.

Note that transform.position is a Vector3. This is not a particular problem but Equals will compare all 3 values. Your currentWaypoint will be converted into a Vector3 with z being set to 0. Just be aware of possible issues.

To track down the issue I would confirm that you never run more than one coroutine at a time and that no other code is messing with the objects position while the coroutine runs. You can print out Time.frameCount along with your debug.log message. It helps to track down multiple iterations per frame.

Since we don’t know when and how you start your coroutine we can’t say much more about your issue.

The problem was solved by bumping up linear drag up to 100 or more. A silly problem and even sillier solution. But hey, it works