Using Unity 5, I want to use have one keyboard key ("f") increase a counter when pressed. It means, using Input.GetKeyDown("f") function in a way that: if "f" is pressed when the counter=1, then the counter is set to be equal 2. If counter was equal 2 when "f" is pressed, then counter is set to 3.
However, it does not work properly: it seems that Unity detects the key being pressed many times, no matter if it was only pressed once. See the code that illustrates the situation:
using UnityEngine;
using System.Collections;
public class TestingKeyGetRecursion : MonoBehaviour {
int counter = 1;
void Update () {
if(counter == 1 && Input.GetKeyDown("f"))
{
counter = 2;
Debug.Log(counter);
}
if(counter == 2 && Input.GetKeyDown("f"))
{
counter = 3;
Debug.Log(counter);
}
if(counter == 3 && Input.GetKeyDown("f"))
{
counter = 1;
Debug.Log(counter);
}
}
void OnGUI()
{
GUI.Label(new Rect(30, 10, 250, 20), "counter: " + counter.ToString());
}
}
As you can see in the console if you run the above example, the values are properly set into the counter variable and printed in the console. However, it happens several times in the same key-hit and, in the end, the counter ends up equal as it started, i.e. equal 1.
Can anyone please explain:
1) why does the Engine behave like that;
2) is there a way to solve such situation? I cannot substitute the counter with a bool variable and just do "counter != counter" when "f" is pressed.