- Home /
Input.GetKeyUp Don't work to detect release of key
I have searched and seen several answers, but i cant get it to work. The code wont print the button up message, so i assume that i am missing something.
I am trying to make a function for Interaction and when you release the button it should confirm your choice of action. Similar to a weapon selection wheel.
Update
void Update()
{
switch (isAiUnit)
{
case true:
{
AiInput();
}
break;
case false:
{
PlayerInput();
}
break;
}
}
void PlayerInput()
{
if(Input.GetKey(KeyCode.E))
{
if(Input.GetKeyDown(KeyCode.E))
{
interactionTimeStart = Time.time;
}
InteractionInput(interactionTimeStart);
}
}
void InteractionInput(float timeStart)
{
Debug.Log(" Button Down " + (Time.time - timeStart));
if (Input.GetKeyUp(KeyCode.E) && ((Time.time - timeStart) > 0.25f))
{
Debug.Log(" ButtonUp ");
}
}
Answer by HellsHand · Apr 21, 2021 at 08:02 PM
In your check you are using &
which is a bitwise operator, use &&
instead.
Ok with that the next step I would try is removing the Time.time - timeStart
just to check if it's actually KeyUp
that's an issue. Though looking again, InteractionInput
is being called during GetKey
, this most likely will never work since GetKeyUp
is only true on the frame the key was released and if the frame reads GetKey
I don't believe it will get the key co$$anonymous$$g up in the same frame. Something you could test is change the key for GetKeyUp
and see if it triggers while holding e
Try this:
void PlayerInput()
{
if(Input.GetKeyDown(KeyCode.E))
{
interactionTimeStart = Time.time;
}
else if (Input.GetKeyUp(KeyCode.E))
{
InteractionInput(interactionTimeStart);
}
}
then
void InteractionInput(float timeStart)
{
Debug.Log(" Button Down " + (Time.time - timeStart));
if (Time.time - timeStart) > 0.25f)
{
Debug.Log(" ButtonUp ");
}
}
Answer by unity_ek98vnTRplGj8Q · Apr 21, 2021 at 08:42 PM
You are calling InteractionInput() from inside of the brackets around if(Input.GetKey())
. On the frame that the button is released, however, Input.GetKey() will be false so InteractionInput() will never be called. You need to check for GetKeyUp outside of GetKey