Limiting the distance of an animated translation?

Hey there folks,

I’ve created this simple code that is an activated animation to open/close a sliding door when it’s been clicked (well, when the right click is being held down to close it, it also has a seperate script that is almost identical to hold down left click to open it).

I want to be able to limit the distance the door can close, naturally; how can I expand on this code to make it do so?

C#

    using UnityEngine;
    using System.Collections;
    
    public class cabdoorclose : MonoBehaviour
    {
    	
    public void OnDoorclose()
    	{
            transform.Translate(Vector3.forward * Time.deltaTime);
        }
    }

This is the clickable object to open/close the door:

C#

using UnityEngine;
using System.Collections;

public class cabdoorclick : MonoBehaviour
{
	public cabdooropen dooropen;
	public cabdoorclose doorclose;
	void OnMouseEnter ()
	{
		guiText.text = "Hello World!";
	}
	void OnMouseOver ()
	{
		if (Input.GetMouseButton (1)) {
		doorclose.OnDoorclose();
		}
		if (Input.GetMouseButton (0)) {
		dooropen.OnDooropen();
		}
	}
}

Well assuming the translation of the door is on one axis, in your case it looks like Z, you can just add 2 float variables (minimum maximum) and an if statement.

public void OnDoorclose()
{
    if (transform.localPosition.z < maximum);        //maximum  = z value the door is capable of going to (since your close method is going in +z direction your maximum is counter intuitively your close amount, and minimum is your open amount.... you might want to flip this simply for readability)
        transform.Translate(Vector3.forward * Time.deltaTime);
}

The OnDoorOpen() method will be the same but using

if (transform.localPosition.z > minimum)
    transform.Translate(Vector3.back * Time.deltaTime);

For this to work you will need your door object to be a child of another gameObject, that way you can count on the localPosition to be relative to its parent object.