About OnTriggerStay and Input.GetKeyDown

Hello everyone.
To go directly to the point, I’m having a bit of trouble with this code.
It seems that once I press the interactableKey (“E”) and the InputGetKeyDown returns true, it stays true for about 6 executions of the OnTriggerStayMethod, they are not synchronized and so It breaks my code.

Expected behavior:
Player presses “E” when isHiding is false and statement 1 executes,and so isHiding is set to true.
Player pressed “E” when isHiding is true and statement 2 executes, and so isHiding is set to false.

Actual behavior:
Player presses “E” when isHiding is false, statement 1 executes and sets isHiding to true and then immediately after this, statement 2 is also executed, because isHiding was set to true and apparently the return value for the Input.GetKeyDown is still true for a few OnTriggerStay execution frames. Which breaks my code.

This is the code:
private void OnTriggerStay() { //Statement 1 if (Input.GetKeyDown(interactableKey) && this.isLocker && !PlayerManager.Instance.isHiding) { PlayerManager.Instance.currentHidingSpot = this.gameObject; PlayerManager.Instance.PerformHide();//This sets isHiding to true return; // This should be preventing the next if statement from being evaluated } //Statement 2 if (Input.GetKeyDown(interactableKey) && this.isLocker && PlayerManager.Instance.isHiding) { PlayerManager.Instance.PerformExitHide(); //This sets isHiding to false } }
I am sorry if this is confusing, I don’t usually ask questions here but I’ve never came across a problem quite like this one. Let me know your thoughts.

Hello there. This may be happening because the OnTriggerStay function runs in FixedUpdate and can happen multiple times in one frame, if I’m not mistaken. Anyway, you should try to move your Input functions outside of OnTriggerStay and put them inside the Update() function to track user input.

Hope that helps.