- Home /
Trying to write a function that checks if 2 keys are pressed
So I'm trying to write a function that checks if 2 keys are pressed within 1 second if each other:
bool IfTwoKeysPressed(string Key1, string Key2)
{
float FirstKeyPress = 20;
float SecondKeyPress = 50;
float TimePressedDelay = 1;
bool KeysPressed = false;
if (Input.GetKeyDown(Key1))
{
FirstKeyPress = Time.time;
}
if (Input.GetKeyDown(Key2))
{
SecondKeyPress = Time.time;
}
if (Mathf.Abs(SecondKeyPress - FirstKeyPress) <= TimePressedDelay)
{
FirstKeyPress = 20;
SecondKeyPress = 50;
KeysPressed = true;
}
Debug.Log(KeysPressed);
return KeysPressed;
}
Problem is when I call this function in Update(), checking the delay between the 2 presses doesn't work since the function happens within 1 frame and resets. Transferring the code into Update() works but in my game I'm going to have to check a lot of key combinations and would prefer not having to creating all the variables and writing this code every time.
Answer by michi_b · Dec 04, 2018 at 05:11 PM
You have to store the last times the keys have been pressed manually. Then, each time a new key has been pressed, check if all the keys have been presses in your time frame (1 second). Let me give you a helper class that manages that:
using System;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class MultiKeyPressChecker
{
[Serializable]
private class KeyData
{
[SerializeField, Tooltip("key that has to be pressed to trigger")] private KeyCode key = KeyCode.A;
[SerializeField]private float lastPressTime = float.NegativeInfinity;
public void Update()
{
if (Input.GetKeyDown(key))
{
lastPressTime = Time.time;
}
}
public bool GetWasPressed(float timeFrame)
{
return Time.time - timeFrame < lastPressTime;
}
public void ClearLastKeyPressTime()
{
lastPressTime = float.NegativeInfinity;
}
}
[SerializeField, Tooltip("keys that have to be pressed in the timeframe to make the check trigger")]
private List<KeyData> keys;
[SerializeField, Tooltip("duration in which all specified keys have to be pressed")]
private float timeFrame = 1f;
public bool Check()
{
foreach (KeyData key in keys)
{
//update last press times of keys
key.Update();
}
foreach (KeyData key in keys)
{
//if any of the keys was not pressed in the timeframe, return false
if (!key.GetWasPressed(timeFrame))
{
return false;
}
}
//else clear last key presses and return true (all keys have been pressed in the timeframe)
foreach (KeyData key in keys)
{
key.ClearLastKeyPressTime();
}
return true;
}
}
You can use this helper class like in this example script:
using UnityEngine;
public class MultiKeyPressExample : MonoBehaviour
{
[SerializeField] private MultiKeyPressChecker keyPressChecker;
private void Update()
{
if (keyPressChecker.Check())
{
Debug.Log("all the specified keys have been pressed in the timeframe");
}
}
}
Just assign the keys you are interested in and the allowed timeframe in the inspector and you are good to go.
Hey again So this worked great, but now I've run into the problem that you can just press all the buttons on the keyboard and as long as those buttons contained the required keys, the action happens. Any ideas on how to fix this?
Answer by Vega4Life · Dec 04, 2018 at 05:27 PM
I created a double key press script. Thus, if other scripts need to use it, just add it and check for the keys you need. I also changed a few lines of code as well, as I don't think you need to keep time for each button press.
using UnityEngine;
// I wouldn't worry about time for each key. You just need a global time from the last one clicked
public class DoubleKeyPress : MonoBehaviour
{
bool key1Pressed;
bool key2Pressed;
float countDownSinceKeyPressed = 0;
float TimePressedDelay = 1;
public bool IfTwoKeysPressed(KeyCode key1, KeyCode key2)
{
countDownSinceKeyPressed -= Time.deltaTime;
if (countDownSinceKeyPressed <= 0)
{
key1Pressed = false;
key2Pressed = false;
}
if (Input.GetKeyDown(key1))
{
countDownSinceKeyPressed = TimePressedDelay;
key1Pressed = true;
}
if (Input.GetKeyDown(key2))
{
countDownSinceKeyPressed = TimePressedDelay;
key2Pressed = true;
}
if (key1Pressed && key2Pressed) countDownSinceKeyPressed = 0f;
return key1Pressed && key2Pressed;
}
}
Here is a random script that adds it and uses it.
using UnityEngine;
public class UseDoubleKeyPress : MonoBehaviour
{
DoubleKeyPress keyPress;
void Awake ()
{
keyPress = gameObject.AddComponent<DoubleKeyPress>();
}
void Update ()
{
if (keyPress.IfTwoKeysPressed(KeyCode.A, KeyCode.B))
{
Debug.LogError("Buttons Pressed");
}
}
}
yep, for just two keys this works, have to add though that when you use a counter ins$$anonymous$$d of a stored time, you accumulate a floating point precision error, which should be negligible in this context though.
Your answer
![](https://koobas.hobune.stream/wayback/20220612183328im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
when is pysics.raycast used, if it is called in Update() 1 Answer
Movement using Time.deltaTime not working on Fast mac 3 Answers
Slow update best practice 0 Answers
regenerating stats in update(); 1 Answer
My variable doesn't update real-time? 2 Answers