user14531401
user14531401

Reputation:

I need help fixing my code for a secret door

So i am creating a game in unity and I'm trying to make a collider and input based opening system and here is my code:

public class SecretDoor : MonoBehaviour
{

    public GameObject secretDoor;

    public bool open;

    private void OnTriggerEnter(Collider other)
    {
        open = true;

        if (Input.GetKeyDown(KeyCode.T))
        {
            secretDoor.SetActive(false);
        }
    }

    private void OnTriggerExit(Collider other)
    {
        open = false;

        secretDoor.SetActive(true);
    }

}

It isn't opening or closing so I was hoping someone could help me.

Upvotes: 1

Views: 57

Answers (1)

ChilliPenguin
ChilliPenguin

Reputation: 715

The check for an input would only occur when the player touches the door, you may want to look into OnTriggerStay. Warning! I would like to note that the wiki also states that this function does not run on every frame, which can hinder with such ability.

Note that trigger events are only sent if one of the colliders also has a rigidbody attached. Trigger events will be sent to disabled MonoBehaviours, to allow enabling Behaviours in response to collisions.

void OnTriggerStay(Collider other)
{
        //check code here
}

This is with the guess that the open boolean is working as correctly(you should check if it is as you have set it to public.

So the best way it is probably the best to implement the input detection within the update function like this using the open boolean.

void Update(){
    if(open){
        if (Input.GetKeyDown(KeyCode.T)){
           //Stuff here
        }
    }
}

Upvotes: 2

Related Questions