C# countdown timer

I’m trying to create a c# countdown timer for my level which should also be displayed in the GUI. The player needs to destroy certain items to get extra time. If the player runs out of time it’s game over. It the player destroyed all the items they are presented with the time left and then can play again to see if they can finish the level faster with more time remaining.

I’m not sure what the script is to initiate a timer and then count down with seconds. The initial time should obviously be a public parameter you can tweak from inside the editor.

Running out of time should run an if statement to initiate a game over screen for losing. Destroying all the objects should stop the timer and record the remaining time to display in the winning game over screen.

Destroying certain objects will add time to the timer in seconds or fractions of seconds.

So I know what I want to do, but the Syntax is giving me nightmares. :open_mouth: Any help will be appreciated.

1 Like

You could create a script that keeps track of how much time is left.

That object’s update loop can subtract Time.deltaTime from that value, and check if it’s below zero:

var timeLeft = 30;
  
function Update()
{
    timeLeft -= Time.deltaTime;
    if ( timeLeft < 0 )
    {
        GameOver();
    }
}

Other objects could access that value, to display it in the GUI or add to it as needed.

float currCountdownValue;
public IEnumerator StartCountdown(float countdownValue = 10)
{
    currCountdownValue = countdownValue;
    while (currCountdownValue > 0)
    {
        Debug.Log("Countdown: " + currCountdownValue);
        yield return new WaitForSeconds(1.0f);
        currCountdownValue--;
    }
}

To start you need to call:

StartCoroutine(StartCountdown());

Michael,

That’s quite a request, but I like a challenge, so here we go.

Firstly, the structure that probably best suits this is:

  • Game Controller (in charge of game win/loss and messaging)
  • Timer (GuiText object that displays the time left on screen. It is VERY important that Timer is a child of the Game Controller gameobject)
  • Items (the onscreen, destructable items you mentioned. These must also be child objects of the Game Controller)

The Game Controller would look something like this:

using UnityEngine;
using System.Collections;

public float timeIncrease = 2;
public bool timeElapsed = false;

public int items;

void Start()
{
	//Gather how many items are remaining
	GameObject[] items = GameObject.FindObjectsWithTag("items") as GameObject[];
	itemsRemaining = items.length;

	//The timer, as a child of this gameobject, receive this and start the countdown using the timeRemaining variable
	BroadcastMessage("Start Timer", timeRemaining);
}

void Update()
{
	
	if (itemsRemaining == 0)
	{
		//You win!
	}

	if (timeElapsed)
	{
		//You lose!
	}
}

//If the game controller receives this signal from the timer, it will end the game
void timeHasElapsed()
{
	timeElapsed = true;
}

//If the Game Controller receives this signal from a destroyed item,
//  it sends a message to the time object to increase the time left
void itemDestroyed()
{
	increaseTime();
	
}

void increaseTime()
{
	broadcastMessage("timeIncrease", timeIncrease)
}



//I've included this dead function because I can't test the code myself right now and I don't want to leave
// you with errors. IT may or may not be needed, though.
void timeIncrease
{}

The purpose of the Game Controller would be to receive the happenings of both the items and timers and pass the appropriate responses back and forth, as well as handle the win/lose condition.

Then, you would have this script attached to your timer object:

using UnityEngine;
using System.Collections;

public float timeRemaining = 60f;

void Start()
{
	InvokeRepeating("decreaseTimeRemaining", 1.0, 1.0)
}

void Update()
{
	if (timeRemaining == 0)
	{
		sendMessageUpward("timeElapsed");
	}

	GuiText.text = timeRemaining + " Seconds remaining!";

}

void decreaseTimeRemaining()
{
	timeRemaining --;
}

//may not be needed, left it in there
void timeElapsed()
{}

And, in the script for your onscreen items, you would include this:

void OnDestroy()
{
	SendMessageUpwards("itemDestroyed")
}

void itemDestroyed()
{}

I have to apologise in advance, though, I have no ability to test this code right now and I had to crank it out quickly, so it will have errors, but remember, Game Controller is the parent to the timer and items, as they will have to send messages back and forth and, in this code, the game controller will handle that.

I have figured out how to make a countdown timer.

public class StartCountdown : MonoBehaviour
{
	int time, a;
	float x;
	public bool count;
	public string timeDisp;
	  
	void Start ()
	{
		time = 3;
		count = false;
	}

	void FixedUpdate ()
	{
		if (count)
		{
			timeDisp = time.ToString ();
			GameObject.Find ("StartCounter").GetComponent<Text> ().text = timeDisp;
			x += Time.deltaTime;
			a = (int)x;
			print (a);
			switch(a)
			{
				case 0: GameObject.Find ("StartCounter").GetComponent<Text> ().text = "3"; break;
				case 1: GameObject.Find ("StartCounter").GetComponent<Text> ().text = "2"; break;
				case 2: GameObject.Find ("StartCounter").GetComponent<Text> ().text = "1"; break;
				case 3: GameObject.Find ("StartCounter").GetComponent<Text> ().enabled = false;
					count = false; break;
			}
		}
	}
}
float totalTime = 120f; //2 minutes
  
void Update()
{
    totalTime -= Time.deltaTime;
    UpdateLevelTimer(totalTime );
}

public void UpdateLevelTimer(float totalSeconds)
{
    int minutes = Mathf.FloorToInt(totalSeconds / 60f);
    int seconds = Mathf.RoundToInt(totalSeconds % 60f);
  
    string formatedSeconds = seconds.ToString();
  
    if (seconds == 60)
    {
        seconds = 0;
        minutes += 1;
    }
  
    timer.text = minutes.ToString("00") + ":" + seconds.ToString("00");
}

Here’s my countdown timer. Know this is an old thread, but I’m new to scripting and was pleased with myself for figuring this out, so wanted to share. Fairly simple. Modified from a tutorial found here: How to create a Timer [Tutorial][C#] - Unity 3d - YouTube

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Timer : MonoBehaviour
{

    public Text timerText;
    private float startTime;

    private bool timerFinished = false;

    public GameObject gameOverPanel; // Game Over output.

    public float t;

    // Start is called before the first frame update
    void Start()
    {
        startTime = Time.time + 90; //Time in seconds to count down from.
    }

    // Update is called once per frame
    void Update()
    {
        if (timerFinished)      //Timer finished bool.
            return;

        float t = Time.time - startTime; //Time variable.
        
        string minutes = ((int) t / 60).ToString();  //Minutes string.
        string seconds = (-t % 60).ToString(format:"f1"); //Seconds string to one decimal place.

        timerText.text = minutes + ":" + seconds; //Text object output.

        if (t >= 0)                 //Timer stop and Game Over condition.
        {
            TimerStop();
            GameOver();
        }

    //Could also Stop timer with a collider with "IsTrigger" checked by attaching following code in a separate script to the GO with the collider on it.

    /*
    public void OnTriggerEnter(Collider other)
    {
    GameObject.Find("Player").SendMessage("TimerStop");
    }*/

    }

public void TimerStop()
{
timerText.color = Color.magenta;
timerFinished = true;

}
public void GameOver()
{
gameOverPanel.SetActive(true);
Destroy(gameObject);
}
}

I want to pause the game during the countdown ??

Here’s the easy way!

public float timeLeft = 20f;
private bool timePaused = false;

void Update()
{
    if (timeLeft > 0)
    {
        if (!timePaused)
        {
            timeLeft -= Time.deltaTime;
        }
    }
    else
    {
        //Write Game Over code here
    }
}

//Call this function when the player destroy the object. Put the time in secounds you want to increase.
public void IncreaseTime(float timeToIncrease)
{
    timeLeft += timeToIncrease;
}

//Call this function when you want to pause the time. Put the true/false in argument to pause or unpause.
public void PauseTime(bool pause)
{
    timePaused = pause;
}

//It will show the text on GUI
void OnGUI()
{
    GUI.Label(new Rect(10, 10, 200, 30), "Time Left: " + timeLeft.ToString("F2")); // It will show the time on UI with 2 decimal points 
}