About OnTriggerStay and Input.GetKeyDown

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.

Read more here: https://stackoverflow.com/questions/64407834/about-ontriggerstay-and-input-getkeydown

Content Attribution

This content was originally published by Pedro Civa Wiltuschnig at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: