How do I lock x position of a game object?

I want to lock the x position of my gameobject but only for certain values. For example, I want the gameobject to be able to move from x values: -10 to +10, but not anywhere past those values. I don’t want my gameobject moving to -11 or 11, or any higher/lower. Is this possible or would I need to create some sort of collider for a barrier?

You can do:

if(transform.position.x < -10)
    transform.position = new Vector3(-10,transform.position.y,transform.position.z);
if(transform.position.x > 10)
    transform.position = new Vector3(10,transform.position.y,transform.position.z);

Use Mathf.clamp in x argument:

float x=mathf.clamp(transform.position.x,-10,10);
transform.position = new Vector3(x,transform.position.y,transform.position.z);