how do i get a boolean to switch to true only after i've pressed a key three times?
total noob here, im learning unity for my interactive vis class for my masters degree. We've got a wee sample project due at the end of the week and im stuck on something integral to my diorama.
I need to make my boolean switch to 'true' after i've pressed the up key three times so I can then activate a bit of UI - you need to 'chant' a song three times to activate a mystic ruin... I'm completely stuck on how to do it and I know its a really basic question but I'd really appreciate a hand!
As it stands, I press the down key once, it activates a sound and the public bool switches to true. I need to press the down key three times, the sound play on each key down, and then the bool switch to true if that makes sense.
here's my code so far:
public class chanting : MonoBehaviour { public AudioSource chant;
public bool isTrue;
// Start is called before the first frame update
void Update()
{
if (Input.GetKeyDown(KeyCode.UpArrow))
{
chant.Play();
isTrue = true;
}
}
} appreciate any help!
Add comment
Answer by lgarczyn · Oct 21, 2019 at 06:28 PM
Simply have an int counter, that starts as 0. Everytime the key is pressed, increment the counter, then check if it is 3.
Once the counter reaches 3. Reset it, and set your bool to true.
If you want every key press to happen in a small amount of time, every time you get a key press, check that the current time is not too far away from the time of the previous key press.
public bool isTrue;
int pressCounter;
float lastKeyPress;
void Update()
{
if (Input.GetKeyDown(KeyCode.UpArrow))
{
if (Time.time - lastKeyPress < 1f) // no more than 1 sec between key presses
{
pressCounter++;
if (pressCounter >= 3)
{
pressCounter = 0;
[...]
}
}
else
pressCounter = 1;
lastKeyPress = Time.time
}
}
Answer by Peremy · Oct 23, 2019 at 06:51 PM
Thank you that was really helpful! Im at a good stage now, but for some reason my counter counts up in twos instead of one by one - i made it public so i could test and it goes 2 - 4 etc. Any chance you have any insights?
public class chanting : MonoBehaviour
{
public AudioSource chant;
public bool isTrue;
public int count;
// Update is called once per frame
void Start()
{
count = 0;
}
void Update()
{
if (Input.GetKey(KeyCode.UpArrow)) //When up key is pressed, chant soundbite sounds
{
chant.Play();
count = count + 1;
if (count >= 4)
{
count = 4;
}
isTrue = true;
}
}
}
Input.Get$$anonymous$$ey
is true for every frame where the key is pressed, you need Input.Get$$anonymous$$eyDown
Your answer
![](https://koobas.hobune.stream/wayback/20220612213728im_/https://answers.unity.com/themes/thub/images/avi.jpg)