Fix for patrol coroutine code

I also posted this in the Q&A, but thought I would put it here also in case people miss it there.

When I set my waypointWaitTime to a higher value, like 5 seconds, I realized that the code Ben wrote in the video was not working quite correctly. The enemy was waiting for close to double the intended time, especially noticeable if the the waypoints were close together. This is because the Patrol loop was only checking for the distanceToNextWayPoint once per loop (5 seconds in my case).

To fix this I changed my code to as follows, so that the game only waits 5 seconds once the enemy has reached the waypoint, otherwise the game simply waits for end of frame.

My code is slightly different, as I added helper functions to my PatrolPath class, but should be self explanatory.

private IEnumerator Patrol()
{
    character.Walk();
    state = State.Patrol;
 
    int nextWaypointIndex = 0;
    Vector3 nextWaypoint = patrolPath.GetWaypoint(nextWaypointIndex);
    character.SetDestination(nextWaypoint);
 
    while (true)
    {
        float distanceToNextWaypoint = (nextWaypoint - transform.position).magnitude;
        if (distanceToNextWaypoint < patrolPath.ApproachTolerance())
        {
            yield return new WaitForSeconds(waypointWaitTime);
            // Choose next waypoint index, cycling to start if necessary
            nextWaypointIndex = (nextWaypointIndex + 1) % patrolPath.WaypointCount();
            nextWaypoint = patrolPath.GetWaypoint(nextWaypointIndex);
            character.SetDestination(nextWaypoint); 
        }
        else
        {
            yield return new WaitForEndOfFrame();
        }
    }
}

Privacy & Terms