Set limit to transform.translate

I’m making a drawer that on press “e” open and close if the player is in a trigger. The problem come when I open the drawer, it move in x position and don’t stop. How I can set a limit to open? And how I can do that the drawer return to his original position on close? Thanks

using UnityEngine;
using System.Collections;

public class Drawer : MonoBehaviour {

    public float Smooth = 2.0f;
    //public float MaxDistance = 2.0f;
    public bool Enter;
    public bool IsOpen;

	void Start ()
    {

    }

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            Enter = true;
        }
    }

    void OnTriggerExit(Collider other)
    {
        if (other.gameObject.tag == "Player")
        {
            Enter = false;
        }
    }

	void Update ()
    {
        if(IsOpen == true)
        {
            transform.Translate(0, Time.deltaTime, 0);
        }

        if(Enter == true)
        {
            if(Input.GetKeyDown("e"))
            {
                IsOpen = !IsOpen;
            }
        }
    }
}

Well your void Update() is a little bit wrong :wink:

 void Update ()
 {
     if(IsOpen == true && MaxDistance < transform.position.y)
     {
         transform.Translate(0, Time.deltaTime, 0);
     }

     if(Enter == true)
     {
         if(Input.GetKeyDown("e"))
         {
             IsOpen = !IsOpen;
         }
     }
 }

but if you close the drawer, you need to know, where it was at the beginning. Is the starting position of the drawer (0,0,0)?

For your problem, I advise you another solution : Coroutines

In the inspector, just indicate the closed and opened position of your drawer

using UnityEngine;
using System.Collections;

public class Drawer : MonoBehaviour {

public Vector3 OpenPosition ;
public Vector3 ClosePosition ;

private bool canTrigger;
private bool isOpen ;

void OnTriggerEnter(Collider other)
{
	if (other.gameObject.tag == "Player")
	{
		canTrigger = true;
	}
}

void OnTriggerExit(Collider other)
{
	if (other.gameObject.tag == "Player")
	{
		canTrigger = false;
	}
}

void Update ()
{
	if(canTrigger && Input.GetKeyDown("e"))
	{
		isOpen = !isOpen;
		StopAllCoroutines();
		StartCoroutine( slideTo( isOpen ? OpenPosition : ClosePosition) ) ;
	}
}

private IEnumerator slideTo( Vector3 endPosition )
{
	while( Vector3.Distance( endPosition, transform.position ) > 0.1f )
	{
		transform.position = Vector3.Lerp( transform.position, endPosition, Time.deltaTime );
		yield return null;
	}
}