GetKeyDown always returning true resulting an infinite loop

I am wrapping up GetKeyDown into a function as below:

class PlayerInputHandler{

   public static bool TestPInput()
   {
       bool k = GetKeyDown(KeyCode.P);
       return k;
   }
}

and calling in a update function as

void HandleTestInput()
{
   if (PlayerInputHandler.TestPInput())
   {
       Debug.Log("Pressed p");
       HandleTestInput();
   }
}

In my Update as:

void HandleTestInput()
{
   if (PlayerInputHandler.TestPInput())
   {
       Debug.Log("Pressed p");
       HandleTestInput();
   }
}

Q1. How is this going into an infinite Loop ? as I have strictly given the condition

if (PlayerInputHandler.TestPInput())

Also how can this always return true ?
as on the next call, it should be rechecking the input right?

Since I see no loop in your code I wonder why you think this causes an infinite loop.
Also: GetKeyDown(KeyCode.P);
Have you left out Input classname here?
Your 2 last code listing are the same. Have you intended to post something else?

So from what you posted I cannot see a problem. GetKeyDown should only fire the frame when it was pressed. So it’s likely you did something wrong.

You’re causing infinite recursion. HandleTestInput is calling itself on line 6. GetKeyDown true for the entire frame. If you’re infinitely recursing, you’re never leaving the current frame.

3 Likes

Yeah, Thanks

Actually it was the recursion which was happening, my apologies.
I thought GetKeyDown was called everytime when you call it.

But then, if we want to caculate multiple number of inputs in a single frame of that particular keycode, is it a bad practice?

You can’t really call something that crashes your program a practice.

Can’t have multiple number of inputs in a single frame (whatever that means), you either have true or false on specific keycodes (input device buttons) on current frame. You can count for how many frames a key was pressed but thats over multiple frames not a single one and result is dependant on the game’s frame rate.

2 Likes