- Home /
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.
Answer by SerbiX8 · Oct 17, 2020 at 10:25 PM
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.
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Application.targetFrameRate returns -1 value 1 Answer
How to enable gravity on gameobject when interact by player 3 Answers
desktop and mobile pairing 0 Answers