Tutorial: a door that opens by itself

A sliding door that opens when the player comes near and closes behind them. It teaches triggers and tweens.

1. Set up

Set up
  1. Make a door: a flat tall Cube with a collider.
  2. Make sure the player has the tag Player (see Collect coins).
  3. Add a Trigger3D to the door and make it big enough to reach where the player stands in front of it. (Or put the trigger on a second, invisible box in front of the door.)

2. The script

The script

Scripts/SlidingDoor.cs

public class SlidingDoor : Behaviour
{
    public Vector3 slide = new Vector3(0f, 2.4f, 0f);
    public float seconds = 0.6f;

    Vector3 closed;

    public override void Start() { closed = transform.position; }

    public override void OnTriggerEnter(GameObject other)
    {
        if (!other.CompareTag("Player")) return;
        Tween.CancelAll(gameObject);
        Tween.Move(gameObject, closed + slide, seconds, "out");
    }

    public override void OnTriggerExit(GameObject other)
    {
        if (!other.CompareTag("Player")) return;
        Tween.CancelAll(gameObject);
        // wait a moment before closing, so it does not shut on someone's heels
        Tween.Move(gameObject, closed, seconds, "in").After(0.8f);
    }
}

Save it as Scripts/SlidingDoor.cs and add it to the door.

3. How it works

How it works

4. Try it

Try it

Press PLAY and walk to the door. Change seconds in the Inspector for a faster or slower door.

Next: a moving platform.