Looking for Open/Close Script on keypress for animation

Hi there!

Iam looking for a simple open/close on key input script. I try to unfold/fold a foldingtable and bed in a scene. I have both open and close animations, and tried several scripts but i always had trouble with having both animations triggered by 1 keypress (animations got mixed up). I got one script that exactly does what i want, even plays the animation backwards for closing but unfortunately on mouseclick.

using UnityEngine;
using System.Collections;

public class anim : MonoBehaviour {

    public GameObject box;
   
    bool direction = false;

    private void OnMouseDown()
    {
        Debug.Log(direction);
       
        if (!direction)
        {
            box.GetComponent<Animation>()["Bew"].speed = 1;
           
           
        }
        else
        {
            box.GetComponent<Animation>()["Bew"].speed = -1;
           
            //if animation already finisihed, set time to end before playing it backwards
            if(!box.GetComponent<Animation>().isPlaying){
                box.GetComponent<Animation>()["Bew"].time =box.GetComponent<Animation>()["Bew"].clip.length;
               
            }
        }
       
        direction = !direction;
       
        box.GetComponent<Animation>().Play("Bew");
    }
}

Well, its on a private. That could be a problem.

Oh, here. Change private void OnMouseDown to void PlayAnimationNow. Then in the update function do this:

void Update(){
if(playing == false){
PlayAnimationNow();
playing = true;
}
}

And at the end of the animation set playing to false. Try this!