Harry McCoy
Harry McCoy

Reputation: 33

Trying to switch cameras when my Character is in the NPC's collider and button is pressed

I'm currently trying to code a game in which the camera switches when talking with an NPC however it doesn't seem to work when I press down the key when in the collider however it is fine if I remove the GetButtonDown if statement.

    public class NPCInteraction : MonoBehaviour {
    [SerializeField]
    Camera MainCamera;

    void Start()
    {
      MainCamera.GetComponent<Camera>().enabled = true;
    }


       void OnTriggerEnter(Collider other) {

        if (other.gameObject.tag == ("NPC"))
        {
           if (Input.GetButtonDown("Interact"))
            {
                MainCamera.GetComponent<Camera>().enabled = false;
                other.GetComponentInChildren<Camera>().enabled = true;
            }
        }
            }    
void OnTriggerExit(Collider other)
    {
     if (other.gameObject.tag == ("NPC"))
        {
            MainCamera.GetComponent<Camera>().enabled = true;
            other.GetComponentInChildren<Camera>().enabled = false;

        }
    }
}

Upvotes: 0

Views: 78

Answers (1)

Fredrik Widerberg
Fredrik Widerberg

Reputation: 3108

That is because Input.GetButtonDown returns true only the frame the user pressed the button. So you would have to be quite lucky if that's also the same frame that the OnTriggerEnter happened.

Instead, use Input.GetButton

Returns true while the virtual button identified by buttonName is held down.

https://docs.unity3d.com/ScriptReference/Input.GetButton.html

Edit (from comments)

The above solution only works if the key is pressed at the time of the initial collision, to make it work if the key is pressed after that (while still inside the trigger) use OnTriggerStay instead of OnTriggerEnter.

OR

Have a bool toggling with OnTriggerEnter/OnTriggerExit and check for the input in Update

Upvotes: 1

Related Questions