- Home /
How do I make a key activate only when another key is pressed
I'm trying to make a game where the player must alternate between 2 buttons in order to move forward. This is what I have so far.
if (Input.GetKeyDown(KeyCode.A))
{
transform.position += Vector3.up * 0.025f;
}
if (Input.GetKeyDown(KeyCode.D))
{
transform.position += Vector3.up * 0.025f;
}
Thanks!
Answer by ramesh-poreddy · Mar 04, 2019 at 06:49 AM
create a variable named nextAcceptableKey and compare it when ever a key pressed/released.
Here is the snippet you need
private KeyCode nextAcceptableKey = KeyCode.A;
void Update()
{
if (Input.GetKeyDown(nextAcceptableKey))
{
transform.position += Vector3.up * 0.025f;
nextAcceptableKey = (nextAcceptableKey == KeyCode.A) ? KeyCode.D : KeyCode.A;//Assigns alternate keys
}
}
Answer by dan_wipf · Mar 04, 2019 at 05:31 AM
There are 3 input methods to get a KeyPress.
Input.GetKeyDown => when Key is pressed Down
Input.GetKey => when Key is hold
Input.GetKeyUp => when Key is released
To combine two events you need to use the Operator && but this won’t work on down&&down / up&&up / up&&down because you’re not that fast to press two keys in the same frame. so you need to do something like this:
if (Input.GetKeyDown(KeyCode.A) && Input.GetKey(KeyCode.D)){}
I appreciate the help a lot but It's still not perfect. Is there any way to stop a button from being activated until the next button is pressed and vice versa?
hm you might want to use the ! operator before !Input.Get$$anonymous$$ey($$anonymous$$eyCode.D) && Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.A) => this will check that D is not pressed/heldDown when A us Pressed, just use this the Opposite way for D
Your answer
![](https://koobas.hobune.stream/wayback/20220612192856im_/https://answers.unity.com/themes/thub/images/avi.jpg)