How to limit the transform.Translate distance

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();
		}
	}
}

Is this code working? The problem I see is that OnDoorclose() is only called once, but with a Time.deltaTime included, it should be called repeatedly from Update(). One way to move something over time is to use Vector3.MoveTowards():

Here is an example script. In the inspector set v3Open and v3Closed to the positions you want the door in when it is open/closed. Call SetOpenClose() to either open or close the door.

public class OpenClose : MonoBehaviour {
	
	public Vector3 v3Open;
	public Vector3 v3Close;
	public float fDistPerSecond = 1.0f;
	
	private Vector3 v3To;
	
	void Start() {
		v3To = transform.position;
	}
	
	void SetOpenClose(bool bOpen) {
		if (bOpen)
			v3To = v3Open;
		else
			v3To = v3Close;
	}
	

	void Update () {
		transform.position = Vector3.MoveTowards(transform.position, v3To, fDistPerSecond * Time.deltaTime);
	}
}