trouble with opening and closing door with raycasts

so i managed to make a door animation and and I am almost 100% sure that i got the code correct but for some reason when the character tries to open the door it gitters open and then it will refuse to close, can anyone spot what i have done wrong here?

the script on the camera:

public class InteractionControls : MonoBehaviour {
	private RaycastHit hit;

	void Update () {
		Animation anime;
		door Door;

		Physics.Raycast( Camera.main.ScreenPointToRay( Input.mousePosition ), out hit, 10f );
		if (hit.collider.gameObject.tag == "Door") {
			anime = hit.collider.GetComponent<Animation>();
			Door = hit.collider.GetComponent<door>();

			if(Input.GetKeyDown(KeyCode.E)){
				if(Door.state == true){
					anime.Blend ("DoorOpening");
					Door.opendoor();
				}
				if(Door.state == false){
					anime.Blend ("DoorClosing");
					Door.closedoor();
				}
			}
		}
	}
}

and the one on the door:

public class door : MonoBehaviour {

	public bool state;

	public void opendoor(){
		state = false;
	}

	public void closedoor(){
		state = true;
	}
}

I see two problems:

First, you need to check the return value for Physics.Raycast. It returns true or false to indicate whether or not any collider was hit. If nothing was hit, then your hit struct won’t be populated and you can’t safely reference it.

Second, you don’t have any sort of cooldown or lockout on the door. You’ll tell it to open on one frame, then close, then open, then close, rapidly alternating without ever finishing its animation. You can resolve this by giving the door some sort of busy flag, that you update as the animations finish.

Simplest thing would be something like this:

public class door : MonoBehaviour {
    public bool open;
    public bool busy;

    public void opendoor() {
        if (busy) return; //stop if already busy

        //update door status
        open = true;
        busy = true;

        //invoke calls a function after a brief delay (in seconds)
        Invoke("done", 1f);
    }

    public void closedoor() {
        if (busy) return; //stop if already busy

        //update door status
        open = false;
        busy = true;

        //invoke calls a function after a brief delay (in seconds)
        Invoke("done", 1f);
    }

    void done() {
        busy = false;
    }
}