I am confused why my enemy gameobject not following the path i created when not using nested if ?

public class EnemyPathing : MonoBehaviour
{

[SerializeField] List<Transform> wayPoints;
[SerializeField] float moveSpeed = 2f;
// Use this for initialization
int waypointIndex = 0;
void Start()
{
    transform.position = wayPoints[waypointIndex].transform.position;
}

// Update is called once per frame
void Update()
{
    if (waypointIndex <= wayPoints.Count - 2)
    {
        var targetPos = wayPoints[waypointIndex + 1].transform.position;
        var movementThisframe = moveSpeed * Time.deltaTime;
        transform.position = Vector2.MoveTowards(transform.position, targetPos, movementThisframe);
       waypointIndex++ ;

    }

}
};

But when i put waypointIndex ++ into the if statement , enemy gameobject does follow the path i created -
if(transform.position == targetPos)
{
waypointIndex++;
}

Can someone explain what is wrong with the 1st apporach?

You are actually incrementing the “waypointIndex” every frame until it reaches ‘waypoints.count - 2’.

  • As your code is running in Update this will happen in less than a second and then your
    "if (waypointIndex <= wayPoints.Count - 2)" condition will return false and eventually

  • "transform.position = Vector2.MoveTowards(transform.position, targetPos, movementThisframe);"
    This code won’t run and you will end up with having your enemy be stopped at its initial position.

So you should definitely check whether enemy has reached its weapointIndex position or not. And then move to the next weapointIndex if “Reached”.