Question by
alexanderparomenskiy · Mar 22, 2019 at 06:58 AM ·
coroutinetimetimer
Timed button pressed C#
I'm trying to do a piece of code which times you to press certain buttons that appear on the screen, if you do not press them in time you die. However, I'm having some difficulties with Coroutines. Here is my piece of code.
// Update is called once per frame
void Update () {
if (gameActive) {
if (!R_pressed) {
R.SetActive(true);
// start timer
StartCoroutine(Delay_time(R_pressed));
// check if the key is pressed if it go to next if statement
if (Input.GetKeyDown(KeyCode.R))
{
StopCoroutine(Delay_time(R_pressed));
R_pressed = true;
}
}
if (R_pressed && !V_pressed) {
R.SetActive(false);
V.SetActive(true);
StartCoroutine(Delay_time(V_pressed));
// check if the key is pressed if it go to next if statement
if (Input.GetKeyDown(KeyCode.V))
{
StopCoroutine(Delay_time(V_pressed));
V_pressed = true;
}
}
if (R_pressed && V_pressed)
{
V.SetActive(false);
Debug.Log("End Scene Complete");
gameActive = false;
}
}
}
IEnumerator Delay_time(bool button)
{
yield return new WaitForSeconds(1.75f);
if (button == false)
{
gameOver.SetActive(true);
}
}
// checks if the player hit the collider
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player" && !gameActive)
{
// display canvas
CanvasObject.SetActive(true);
gameActive = true;
}
}
Comment
Answer by fafase · Mar 22, 2019 at 07:03 AM
Let's break it down, when the character enters a collider, you want the player to press R within a certain time. then V within a certain time. You already have the triggering so we'll focus on the pressing issue.
We will do without Update.
// checks if the player hit the collider
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player" && !gameActive)
{
// display canvas
CanvasObject.SetActive(true);
StartCorountine(CheckPress());
}
}
IEnumerator CheckPress()
{
float timer = 1.75f;
bool success = false;
while( success == false && timer > 0f )
{
timer -= Time.deltaTime; // reduce timer
success = Input.GetKeyDown(KeyCode.R);
yield return null;
}
if(success == false)
{
Debug.Log("Lost");
yield break;
}
success = false;
timer = 1.75f;
while( success == false && timer > 0f )
{
timer -= Time.deltaTime; // reduce timer
success = Input.GetKeyDown(KeyCode.V);
yield return null;
}
if(success == false)
{
Debug.Log("Lost");
yield break;
}
Debug.Log("Won");
}
The code repeats itself so it could benefit some extra methods to group repetition together. I kept it simple so it is easy to understand.