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?