I'm making a 2D platformer with Unity and I'm trying to create a pressure pad to open a door. I want the door to open when the player is on the pressure pad and close a few seconds after the player leaves it. I've tried different ways, but none of them have worked. In this case, the door should open upwards and close downwards. Also, I've already created some animations (idle, open, and close) for the door, but I don't know how to connect these two objects and then play the animations with proper timing. Thank you in advance.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class PressurePad: MonoBehaviour
{
public UnityEvent OnActivate;
public UnityEvent OnDeactivate;
int objectsInContact;
IEnumerator Timer()
{
yield return new WaitForSeconds(6);
OnDeactivate.Invoke();
}
void OnTriggerEnter2D(Collider2D other)
{
objectsInContact++;
if (objectsInContact == 1 && OnActivate != null) OnActivate.Invoke();
}
void OnTriggerExit2D(Collider2D other)
{
objectsInContact--;
if (objectsInContact == 0 && OnDeactivate != null) OnDeactivate.Invoke();
StartCoroutine(Timer());
}
}
Note: This script was added shortly after the question was posted. Thanks to the first comment under the post, it is mostly made of the code from the answer of this question.