How to set boundaries in enemy 2D movement?

I adapted this code a little from gamesplus james tutorial. I got it a little bit working. I want the enemy to change direction if it hits a wall. In this case, I am using if transform.position.y > some number… because I dont want my enemy to detect wall collision. It kinda works but I think waiting for timeBetweenMoveCounter to reach zero everytime, it misses the timing to change direction. I also don’t want it to read the code reverse direction like 100 times per second. This runs from void update. How do I arrange this?

``````    private float timeBetweenMove = 1;
private float timeBetweenMoveCounter;
private float timeToMove = 2;
private float timeToMoveCounter;

public void RandomMovement()
{
if (IsAlive)
{
if (isPatrolling)
{
timeToMoveCounter -= Time.deltaTime;
MyRigidbody.velocity = Direction;

if (timeToMoveCounter < 0f)
{
isPatrolling = false;
timeBetweenMoveCounter = Random.Range(timeBetweenMove * 0.75f, timeBetweenMove * 1.25f);
}
}
else
{
timeBetweenMoveCounter -= Time.deltaTime;
MyRigidbody.velocity = Vector2.zero;

if (timeBetweenMoveCounter < 0f)
{
isPatrolling = true;
timeToMoveCounter = Random.Range(timeToMove * 0.75f, timeBetweenMove * 1.25f);

Direction = new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f) * MoveSpeed).normalized;

if (transform.position.y > 6.5f)
{
Debug.Log("max y");
Direction = new Vector2(0f, -2f);
}
else if (transform.position.y < -10)
{
Debug.Log("mix y");
}
}
}
}
}
``````

Its really actually easy to solve but i just wanna see your ideas how you would set this up. You dont really need to have advance knowledge of c#