How can I check the latest key that the user pressed?
For example, when the user presses A, it will write “A”
Then when the user presses B, it will only write “B”, and will stop writing “A”.
Here’s an example of what I’m trying to say:
if(Input.GetKey(KeyCode.A))
{
Debug.Log ("A");
}
if(Input.GetKeyUp(KeyCode.B))
{
Debug.Log ("B");
}
//What I want to happen is:
//When the user presses A first, then B next, it will only write B, and not A.
//When the user presses B first, then A afterwards, it will only write A, and not B. It will just completely stop executing Debug.Log("B")
// BUT, with my current code, it will still execute both A and B even though I pressed A first, then B next, or vice versa. I only want one to be executed even though I’m pressing both keys, and the one the should be executed is the latest key I’ve pressed.
This works. In the case where you hold down A, then hold down B, but then let go of B, if you do NOT want A to be printed out, just remove the last else statement with the while loop. You can also remove the stack variable. I used a stack to give you a more flexible implementation in case you want to add more inputs.
using UnityEngine;
using System.Collections.Generic;
public class InputProcessor
{
private Keycode latestKey;
private Stack<KeyCode> stack = new Stack<KeyCode>();
void Update()
{
if( Input.GetKeyDown(KeyCode.A) )
latestKey = KeyCode.A;
else if( Input.GetKeyDown(KeyCode.B) )
latestKey = KeyCode.B;
if ( Input.GetKey(latestKey) )
Debug.Log( latestKey );
else
while (stack.Count != 0)
{
latestKey = stack.Pop();
if (Input.GetKey(latestKey))
{
Debug.Log( latestKey );
break;
}
}
} //end of function Update
} //end of class InputProcessor
its technically known as radio buttons.
this should work:
var ab = 4;
if keydown a, ab = 0;
if keyup a and ab = 0, ab = 4;
if keydown b , ab = 1;
if keyup b and ab = 1, ab = 4;
if ab = 0 print a
if ab = 1 print b
you can also use a ab++ to count frames that it is pressed.
perhaps try more like this:
laskeydown int = 0;
if keydown a, lastkeydown = 1
if keydown b, laskeydown = 2
if keyup a and lastkeydown = 2, do nothing
if keyup a and lastkeydown = 1, lastkeydown = 0
if keyup b and lastkeydown = 1, do nothing
if keyup b and lastkeydown = 2, lastkeydown = 1