Hello, I’m very new to Unity and am making my first game.
It’s a very simple game where you click a circle to make it go down to the floor. As you play the circle will go up at random times and you’ll need to click it. If the circle stays above the ground for more than 3 seconds, or you click it while it’s still on the ground, you get a game over. However, I have it so whenever it goes up it waits 3 seconds before checking if it’s still up, and if it’s still up it gives you a game over.
But it keeps going up, then when I click it and it goes down, the 3 second counter continues and it sometimes goes back up just as the 3 second counter is about to end, giving me an undeserved game over.
Is there any way I can stop this from happening?
Perhaps a way to stop the timer when I click the circle?
Or maybe a completely different way to do this that works better?
Please help me if any of you know how! I pasted the code below so you can see what I did wrong.
Edit: I changed the code a bit and added comments to make it more clear on what I want to do.
public class Peeker : MonoBehaviour
{
// Establish Publics
public bool peeking;
public float timeTillLose;
public bool hardMode;
void Update()
{
// Check if Peeking
if (peeking == false)
{
// Peek at random times
transform.position = new Vector3(0, -4, 0);
if (Random.Range(0, 1000) == 0)
{
peeking = true;
}
}
// Start Timer, if timer ends then the player loses
if (peeking == true)
{
transform.position = new Vector3(0, -1, 0);
StartCoroutine(timeTillOver());
IEnumerator timeTillOver()
{
yield return new WaitForSecondsRealtime(timeTillLose);
if (peeking == true)
{
Debug.Log("Game Over!");
}
// If player presses the left mouse button then the timer stops and the player doesn't lose
if (Input.GetMouseButtonDown(0))
{
StopCoroutine(timeTillOver());
}
}
}
}
void OnMouseDown()
{
// When clicked peeking is set to false
if (peeking == true)
{
peeking = false;
}
// If clicked when not peeking, the player loses
else
{
Debug.Log("Game Over!");
}
}
}