Kind of Lag in movement

Hello there , I have a guarding script in which enemy patrol around specific area and I have provided waypoints to the gameobject but the problem is that it movies like the game is lagging . Its movement is not smooth . I have made a coroutine and did “Startcoroutine” in START() function .
Following is my code

IEnumerator FollowWayPoint(Vector3 waypoints)

    //set the enemy position to first wayPoint
    transform.position = waypoints[0];
    int targetPointIndex = 1;
    Vector3 targetPoint = waypoints[targetPointIndex];

    while (true)
        // Make the enemy move towards the target Point. 
        transform.position = Vector3.MoveTowards(transform.position, targetPoint, speed * Time.deltaTime);
        // When Enemy is on the target Point .
        if(transform.position == targetPoint)
            // Increase the targetPointIndex by 1.
            targetPointIndex = (targetPointIndex + 1) % waypoints.Length;
        targetPoint = waypoints[targetPointIndex];
        yield return new WaitForSeconds(waitTime);

Its probably cause you are using

yield return new WaitForSeconds(waitTime);

and not having it on Update(); , i would reccomend Vector3.MoveTowards having it on Update();.

Hello there,

What @Thaun_ said above is correct. You need to replace yield return new WaitForSeconds(waitTime); with yield return null;.

Now if you want your AI to wait a little when reaching the target waypoint, you would put that yield return new WaitForSeconds(waitTime); line inside your IF statement if(transform.position == targetPoint). That way, when your AI reaches their target, they wait for a while, then start moving to the next target.

Also, in that IF statement I would recommend using a distance check instead of “==”, as it may be very imprecise depending on your speed.

I hope that helps!