Checking if any key is up?
My code for key down
if (Input.anyKeyDown() ){
KeyDownMethod();}
but is there any way to check if any keys are released so an anykeyup. Thanks.
Answer by Danielori · Sep 21, 2015 at 04:57 AM
This may help you.
bool holdingDown;
void Update () {
if (Input.anyKey) {
Debug.Log("A key is being pressed");
holdingDown = true;
}
if (!Input.anyKey && holdingDown) {
Debug.Log("A key was released");
holdingDown = false;
}
}
It doesn't work for individual keys, but close enough.
Answer by ellioman · Sep 15, 2016 at 02:48 PM
Could use the UnityGUI event calls in OnGUI()...
private void OnGUI()
{
Event e = Event.current;
if (e.type == EventType.KeyDown)
{
if (Input.GetKeyDown(e.keyCode))
{
Debug.Log("Down: " + e.keyCode);
}
}
else if (e.type == EventType.keyUp)
{
if (Input.GetKeyUp(e.keyCode))
{
Debug.Log("Up: " + e.keyCode);
}
}
}
More info: https://docs.unity3d.com/ScriptReference/Event.html
Answer by chrisrwingate · Feb 21, 2018 at 02:39 AM
Since this is the first thing that comes up in a search, I figured I'd offer a solution since one doesn't seem to be provided by Unity.
The example will detect any key when it is pressed or held as well as detect when one of those buttons is released. This code also detects what specific keys are being pressed/released.
public class GameInput : MonoBehaviour
{
protected List<KeyCode> m_activeInputs = new List<KeyCode>();
public void Update()
{
List<KeyCode> pressedInput = new List<KeyCode>();
if (Input.anyKeyDown || Input.anyKey)
{
foreach(KeyCode code in System.Enum.GetValues(typeof( KeyCode )) )
{
if (Input.GetKey(code))
{
m_activeInputs.Remove( code );
m_activeInputs.Add( code );
pressedInput.Add( code );
Debug.Log( code + " was pressed" );
}
}
}
List<KeyCode> releasedInput = new List<KeyCode>();
foreach(KeyCode code in m_activeInputs)
{
releasedInput.Add( code );
if(!pressedInput.Contains(code))
{
releasedInput.Remove( code );
Debug.Log( code + " was released" );
}
}
m_activeInputs = releasedInput;
}
}
Wow I just want to thank you for this code snippet. I have been dealing with keybinding pains and this saved me. Everyone says to use OnGui() "Event.current" but Event doesn't catch $$anonymous$$ouse3+. So until I saw your post I almost gave up haha.
Your answer
Follow this Question
Related Questions
How to detect a keyboard key held down? 2 Answers
Disable Key Using Javascript 0 Answers
Why does this condition keep being true even if its not? 0 Answers
Keypresses blocking each other. 0 Answers
How to use a key as trigger? 2 Answers