- Home /
C# Cannot Stop Coroutines
I have a timer that starts at the beginning of the game and stops when all objects tagged "Pickup" are collected. Everything in this script works fine except for the timer stopping. The game can detect when you have collected all of the cubes, but the timer does not stop. It keeps counting. Here is my script:
using UnityEngine;
using System.Collections;
public class Collect : MonoBehaviour {
public int CubesCollected;
public int TotalCubes;
private int Seconds;
private int Minutes;
public GUIText CubeCounter;
public GUIText WinText;
public GUIText Timer;
void Start () {
TotalCubes = 30;
CubesCollected = 0;
CubeCounter.text = ("Cubes Collected: 0 / " + TotalCubes.ToString ());
WinText.text = ("");
Timer.text = ("0:00");
StartCoroutine("TimerFunction");
}
IEnumerator TimerFunction () {
while(true) {
yield return new WaitForSeconds(1);
Seconds++;
if(Seconds == 60) {
Seconds -= 60;
Minutes++;
}
if(Seconds <= 10) {
Timer.text = (Minutes.ToString() + ":0" + Seconds.ToString());
}
if(Seconds >= 10) {
Timer.text = (Minutes.ToString() + ":" + Seconds.ToString());
}
}
}
void OnTriggerEnter (Collider other) {
if(other.gameObject.tag == "Pickup") {
other.gameObject.SetActive (false);
CubesCollected++;
CubeCounter.text = "Cubes Collected: " + CubesCollected.ToString () + " / " + TotalCubes.ToString ();
if(CubesCollected == TotalCubes) {
StopAllCoroutines();
WinText.text = ("Challenge Completed");
}
}
}
}
I have tried yield break, StopCoroutine("TimerFunction"), but nothing works. The timer just keeps counting. Any ideas?
Answer by poncho · Jul 25, 2014 at 09:46 PM
you can change your while condition from while(true) to while(IwantToRoutineWork), and then just turn off your IwantToRoutineWork flag and it will cease to work
Your answer
![](https://koobas.hobune.stream/wayback/20220613155007im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Music Wont Stop From Page Script+ Extra Problom 1 Answer
Stop camera movement when paused? 0 Answers
c# enum wont show in inspector 3 Answers
Instantiation Wont Stop 1 Answer
enemy explode 2 Answers