- Home /
The question is answered, right answer was accepted
KeyCode Input doesnt work.
Hello, I wrote the code for my 2D project that should open the door and disable the black screen in the next room once button F is pressed.
{
Button.enabled = false;
BlackScreen.enabled = true;
}
private void OnTriggerEnter2D(Collider2D collider2D)
{
if (collider2D.gameObject.tag == "MAIN_Hero")
{
Button.enabled = true;
if (Input.GetKeyDown(KeyCode.F))
{
BlackScreen.enabled = false;
}
}
}
The code doesn't show any mistakes, however the Key F isn't working. I checked if it was a problem with UI but everything was working perfectly. Am I missing something? `
Is the OnTriggerEnter2D called and hits $$anonymous$$AIN_hero at the time you are pressing the F-key? You only test for the F-key at that one time...
Answer by Getsumi3 · Feb 14, 2020 at 01:49 PM
First. Use code tags to format the code properly in your answer. It is really hard to read it
Second. You're trying to call GetKeyDown in OnTriggerEnter. This will not work. I mean. It probably can work but only at the moment you enter the trigger and hardly spamming F at this time and hopping to catch the right frame.
Solution: Change from OnTriggerEnter() to OnTriggerStay()
Thank you, it worked! Sorry for the lack of code tags, it is my first time on this kind of website. I've started it as a hobby not long ago so I apologize if the answer was too simple. Thanks again.
Answer by tormentoarmagedoom · Feb 14, 2020 at 01:54 PM
Hello.
As Getsumi says, you should read about OntriggerEnter and OntriggerStay.
Trying to detect the user pressing a key at the exact frame that colliders start colliding is almost impossible.