Need help with OnTriggerStay() and GetKeyDown()

I have a javascript with a .GetKeyDown() function inside OnTriggerStay(), the purpose of which is to execute a block of code when the “E” key is pressed while the trigger is active. It works fine, only most of the time, the code is executed four times. I have NO idea why this could be. I used Debug.Log and sometimes when the code is executed it is logged four times and sometimes only once.

function OnTriggerStay() {
 if(Input.GetKeyDown(KeyCode.E)) {
  Debug.Log("KEY PRESSED");
 }
}

This is an outline of the code and KEY PRESSED is often logged four times. :face_with_spiral_eyes:

1 Like

Check for Input in Update instead and use OnTriggerStay to toggle a bool saying if it should be checking for Input or not.

1 Like

OnTriggerStay is run like FixedUpdate (since it involves physics), so none of the *Down or *Up events will work correctly inside it for the same reason that they won’t work right in FixedUpdate. All *Down and *Up functions must only be used in Update, or coroutines that run every frame.

–Eric

3 Likes

What is the reason that they don’t work correctly? - Could you elaborate a bit more? - Thanks.

This is a incredibly late response but just in case anyone was having the same issue.
Fixed update doesnt run every frame like Update it runs a fixed amount of time per second, so if you are looking for an input during fixed update and the fixed update isn’t ocurring at the same time as the input key down it wont detect the input since it isn’t ocurring at the same time.

1 Like

Just to clarify, FixedUpdate() runs every Physics update, while Update() runs every frame. Input.GetKeyDown() only returns true the exact Update() frame that it is pressed, and since they’re not perfectly in sync, sometimes when you press the key it won’t register, or will register multiple times. Input.GetKey() should still work as expected though, since it returns true the entire time the key is pressed down (although, is used for different purposes).

2 Likes