Moving obstacle only works if set to move in a huge range

Hello fellow unity users -
I am making my first very simple game where a ball rolls up a hill avoiding obstacles along the way, and I wanted to integrate obstacles that move from side to side on the path. The code for it works, but only if I set the maxTransform to 100 or more, and I only want it to be like 5.

Here is the code I am using:
at first it wasn’t working, but when I made the if statement x and the else statement z it started to work side to side with only the problem I mentioned above. Any ideas? Thanks for reading :slight_smile:

public class ObstacleMovement : MonoBehaviour
{
public float speed = 1f;
public float maxTransform = 5f;
public float minTransform = -5f;

void Update()
{
    transform.Translate(speed * Time.deltaTime, 0, 0);
    checkDirection();
}

public void checkDirection()
{
    if(transform.position.x >= maxTransform)
    {
        speed = speed * -1;
    }

    else if(transform.position.z <= minTransform)
    {
        speed = speed * -1;
    }
    
}

}

Because if your gameobject is already in one of the two conditions it will switch its speed continuously because you are using world space position. Also you are checking for x in the first if and z in the second you should check for x in both.