Platformer Patroler Code Help

So I’m making my first game (2D platformer) and I wanted to make my enemies patrol (walk to the left then turn right before the left edge and walk to the right until the right edge and so on).

I created two empty objects (one near the bottom left and one near the bottom right) as children of my enemy prefab (groundEndsRight and groundEndsLeft). Unfortunately, when the enemy gets to the edge, it starts glitching and stuttering. I figured out that it’s because it is moved to the opposite position by one of the conditionals, then tries once again to move in the opposite direction (ie, when colliderLeft is null, it will move to the right, but then colliderLeft != null and now it moves to the left again and gets trapped in this “loop”). Couldn’t think of a solution though.

Any solutions to this or do I have to scrap my code and find another way to create a patroller enemy?

void Move()
{
Collider2D colliderRight = Physics2D.OverlapCircle(groundEndsRight.position, checkGroundRadius, groundLayer);
Collider2D colliderLeft = Physics2D.OverlapCircle(groundEndsLeft.position, checkGroundRadius, groundLayer);

if (colliderRight != null && colliderLeft == null)
{
//movement to the right
Vector2 position = transform.position;
position.x = position.x + x;
transform.position = position;
}
else
{
//movement to the left
Vector2 position = transform.position;
position.x = position.x - x;
transform.position = position;
}
}

Easiest way is to just create a float stating the x position in where they should turn left and right.

float left = 0;
float right = 100;
bool patrolDir = false; //default left
if(transform.position.x <= left)
{
//turn and patrol right
patrolDir = true;
}
else if(transform.position.x >= right)
{
//turn and patrol left
patrolDir = false;
}

https://www.youtube.com/watch?v=aRxuKoJH9Y0

Blackthornprod’s video will help you.