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 Update()
{
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?
CodePudding user response:
Returns true during the frame the user starts pressing down the key identified by the key KeyCode enum parameter.
This means as long as you are in the same frame this still returns true
!
Your issue has little to do with the input itself but rather the fact that HandleTestInput
is calling HandleTestInput
and between these two calls no frame passes
=> There is no way that GetKeyDown
returns a different value within the same frame.
This is not really an infinite loop though, but rather will throw a StackOverflowException
after enough recursion.
If you rather actually wanted to do something while the key stays pressed you rather want to use Input.GetKey
Returns true while the user holds down the key identified by the key KeyCode enum parameter.
like e.g.
class PlayerInputHandler
{
public static bool TestPInput()
{
return GetKey(KeyCode.P);
}
}
and then
private void HandleTestInput()
{
if(PlayerInputHandler.TestPInput())
{
// In general do NOT log something every frame!
Debug.Log("p is pressed");
}
}