c# - Make something happen if I press a sequence of keys
How can I make for example my player run faster (which would be speed = speed + 15;) after I press a sequence of keys, not at the same time but one after another? For example, if (Input.GetKeyDown (KeyCode.C, KeyCode.B, Keycode.P)); {speed = speed + 15;} ? That doesn't work so I need someone to help me do this Thank you in advance
Answer by NoseKills · Feb 23, 2016 at 07:18 AM
private KeyCode[] sequence = new KeyCode[]{
KeyCode.A,
KeyCode.B,
KeyCode.C};
private int sequenceIndex;
private void Update() {
if (Input.GetKeyDown(sequence[sequenceIndex])) {
if (++sequenceIndex == sequence.Length){
sequenceIndex = 0;
// sequence typed
}
} else if (Input.anyKeyDown) sequenceIndex = 0;
}
That should give you an idea. Written on my phone so I don't have intellisense etc. so it might have typos/syntax errors :-/
Answer by rushikesh988 · Feb 23, 2016 at 06:53 AM
@Mokenister Following code might help you .
using UnityEngine;
using System.Collections;
using System.Diagnostics;
public class KeySequenceDetector : MonoBehaviour {
bool KeyCPressedBefore = false, KeyBPressedBefore = false;
void Start()
{
}
void Update()
{
if (Input.anyKeyDown)
{
if (Input.GetKey("c") || KeyCPressedBefore)
{
if (Input.GetKey("c"))
KeyCPressedBefore = true;
else {
if (Input.GetKey("b") || KeyBPressedBefore)
{
if (Input.GetKey("b"))
KeyBPressedBefore = true;
else {
if (Input.GetKey("p"))
{
//Do Something After Detection of Sequence
UnityEngine.Debug.Log("Sequence Detected of c-b-p");
}
else
{
KeyBPressedBefore = false;
KeyCPressedBefore = false;
}
}
}
else
{
KeyBPressedBefore = false;
KeyCPressedBefore = false;
}
}
}
else
{
KeyCPressedBefore = false;
}
}
}
}
Answer by EmHuynh · Feb 23, 2016 at 07:41 AM
Hello, @Mokenister.
After reading your question, I wrote a class to handle the detection of key sequence.
Here is KeySequence.cs:
using UnityEngine;
using System.Collections;
[ System.Serializable ]
public class KeySequence
{
public KeyCode[] sequence;
private int _sequenceIndex;
private bool _isDetected;
public bool IsDetected() { return _isDetected; }
public KeySequence() { sequence = new KeyCode[ 0 ]; }
public KeySequence( KeyCode[] seq ) {
sequence = new KeyCode[ seq.Length ];
seq.CopyTo( sequence, 0 );
}
public bool Check()
{
if( sequence.Length > 0 )
{
if( Input.GetKeyDown( sequence[ _sequenceIndex ] ) ) { _sequenceIndex ++; }
else if( Input.anyKeyDown ) { _sequenceIndex = 0; }
_isDetected = ( _sequenceIndex == sequence.Length ) ? true : false;
if( _isDetected ) { _sequenceIndex = 0; }
}
else { _isDetected = false; }
return _isDetected;
}
}
KeySequence.cs file: http://bit.ly/1pivoe2
Usage example: http://bit.ly/1QdT9g8