Coroutine to Detect Sequence of Keys

Hi,

So I’m trying to make a game where there are sequences of arrow keys and players have to press them in a specific order

(referenced Waiting for input in a custom function )

public class KeyStuff: MonoBehaviour
{
    void Start()
    {
        StartCoroutine(KeySequence());
    }

    private IEnumerator KeySequence()
    {    
        yield return waitForKeyPress(KeyCode.Space); 
    }

    private IEnumerator waitForKeyPress(KeyCode key)
    {
        bool done = false;
        KeyCode[] sequence = { KeyCode.UpArrow, KeyCode.UpArrow, KeyCode.DownArrow, KeyCode.RightArrow };

        while (!done) 
        {
            if (Input.GetKeyDown(key))
            {
                done = true; 
            }
            yield return null; 
        }
           }

I’m not sure how to detect one key being pressed per call of waitForKeyPress() and advance through the KeyCode array sequence. Any tips?

Thanks

I would do this:

Put the required Keycodes into an array:

KeyCode[] sequence = new KeyCode[]
{
  KeyCode.S,
  KeyCode.E,
  KeyCode.C,
  KeyCode.R,
  KeyCode.E,
  KeyCode.T,
};

Then you don’t need a coroutine, just an integer that you move along from 0 to sequence.Length.

If you press the right key, it goes to the next one.

If you press the wrong key, it goes back to zero.

If you press ALL the right keys, it fires the special thing off.

3 Likes

Be careful to actually check all the keys every frame, not just the correct one in the sequence, since you want to penalize the player if they press the wrong button.

2 Likes

Good point… easy enough to spin through them all with this:

var AllPossibleKeys = System.Enum.GetValues(typeof(KeyCode));

Depends on if OP wants literally ANY key to fail, or just some subset, but yeah you basically iterate over some collection of keys and check GetKeyDown for each.

2 Likes

Oooh another good point… hey OP, run through that list of all KeyCodes and make sure there’s not some weird ones in there, like Alt or mouseclick or who knows what… if you check for those keys and they fire, they will break your sequence.

But when debugging you can always print out the wrong key that did fire, and figure out what might be going down.

1 Like

Got it, thanks for the help!