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.
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.
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.
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: Unity - Scripting API: Event
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;
}
}