Problem with activating a gate multiple times.

Hi all,

I've got a character that I am making open a gate using a collider. I want to be able to switch between the Open and Closed states every time the player collides with the door. I would like to later control this using RayCasting to detect if the player is in range and an Action Button, but I'm new to scripting so taking it slow!

The character currently opens the door when he collides with it, and a timer counts. Then the next time he collides with it, it closes. But then I can't open it again. What have I done wrong? The code is attached. "Frame" is the parent object of "Gate".

private var gateIsOpen : boolean = false;
private var currentDoor : GameObject;

private var gateTimer : float = 0.0;

var gateOpenTime : float = 3.0;
var gateSound : AudioClip;

function Update(){
    if (gateIsOpen){
        gateTimer += Time.deltaTime;
    }
}

function OnControllerColliderHit(hit : ControllerColliderHit){
    if(hit.gameObject.tag == "Gate" && gateIsOpen == false && gateTimer < 3){
    OpenGate();
    }
        if(hit.gameObject.tag == "Gate" && gateIsOpen == true && gateTimer > 3){
    ShutGate();
    }
}

function OpenGate(){
    audio.PlayOneShot(gateSound);
    gateIsOpen = true;
    var myFrame : GameObject = GameObject.Find("Frame");
    myFrame.animation.Play("gateopen");
}

function ShutGate(){
    audio.PlayOneShot(gateSound);
    gateIsOpen = false;
    var myFrame : GameObject = GameObject.Find("Frame");
    myFrame.animation.Play("gateshut");
}

@script RequireComponent(AudioSource)

Thanks in advance! It's doing my head in, but slowly getting to grips with scripting..

You are never resetting the `gateTimer` so it only works in the first 3 seconds of the game.

Here is the updated version of `OnControllerColliderHit` function to fix that issue:

function OnControllerColliderHit(hit: ControllerColliderHit) {
    if (hit.gameObject.tag == "Gate" && !gateIsOpen) {
        OpenGate();
        gateTimer = 0;
    }
    if (hit.gameObject.tag == "Gate" && gateIsOpen & gateTimer > 3) {
        ShutGate();
    }
}

Before switching to `Raycast`, you can also try shutting the door automatically after 3 seconds, by removing the `ShutGate()` from `OnControllerColliderHit()` and updating your `Update()` function:

function Update(){
    if (gateIsOpen){
        gateTimer += Time.deltaTime;

        if (gateTimer > 3) {
            ShutGate();
        }
    }
}