Search The Query
Search
  • Home
  • Unity
  • How to Make Countdown Timer in Unity with Minutes & Seconds
How to Make Countdown Timer in Unity

How to Make Countdown Timer in Unity with Minutes & Seconds

Countdown timers are a common feature in many games, and can be used to create tension, increase player engagement, or simply serve as a way to track time-based events in a game. In this article, we will show you how to create a countdown timer in Unity using C# scripting.

How to Make Countdown Timer in Unity

We will cover the following steps:

  1. Creating a UI Text element in the Unity editor to display the countdown timer.
  2. Writing a C# script that controls the countdown timer.
  3. Adding the C# script to the UI Text element in the Unity editor.
  4. Testing the countdown timer.
  5. Customizing the countdown timer to fit different types of games.

To follow along with this tutorial, you will need Unity installed on your computer, as well as a basic understanding of C# programming. If you’re new to Unity or C#, don’t worry, we’ll explain each step in detail and provide sample code to help you get started.

How to Make Countdown Timer in Unity - Unity IDE
How to Make Countdown Timer in Unity – Unity IDE – Source: unity

Let’s begin by creating a UI Text element in the Unity editor.

1. Creating a UI Text Element:

The first step to creating a countdown timer in Unity is to create a UI Text element. This text element will display the countdown timer on the screen. Here are the step-by-step instructions to create a UI Text element:

How to Make Countdown Timer in Unity -  Unity UI Text Box
How to Make Countdown Timer in Unity – Unity UI Text Box

Step 1: Open the Unity editor and create a new Canvas object by right-clicking in the Hierarchy window and selecting UI > Canvas.

Step 2: In the Canvas object, create a new UI Text object by right-clicking and selecting UI > Text.

Step 3: With the new Text object selected in the Hierarchy window, you can set its properties in the Inspector window. For example, you can set the text content, font size, font color, alignment, and other settings.

Step 4: To position the Text object in the Canvas, you can drag and drop it to the desired location in the Scene view, or use the RectTransform component to adjust its position, rotation, and scale.

Here is an example of C# code that sets the Text component’s font size and color:

using UnityEngine;
using UnityEngine.UI;

public class CountdownTimer : MonoBehaviour
{
    public Text timerText;
    
    void Start()
    {
        // Set the font size and color of the text element
        timerText.fontSize = 36;
        timerText.color = Color.red;
    }
}

In this code snippet, we first declare a public Text variable called “timerText” that will hold a reference to the UI Text object we created in the Unity editor. Then, in the Start() method, we set the font size to 36 and the color to red. You can customize these values to fit your game’s design.

With these steps, you now have a UI Text element that will display the countdown timer on the screen. In the next section, we will write the C# script that will control the countdown timer.

2. Writing the C# Script

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

public class CountdownTimer : MonoBehaviour
{
    public float timerDuration; // The duration of the countdown timer in seconds
    private float timer; // The current value of the countdown timer

    public Text timerText; // The text element that will display the countdown timer

    void Start()
    {
        timer = timerDuration;
    }

    void Update()
    {
        timer -= Time.deltaTime;

        // Check if the timer has run out
        if (timer < 0)
        {
            timer = 0;
            // Add code to handle timer expiration here
        }

        // Convert the timer value to minutes and seconds
        int minutes = Mathf.FloorToInt(timer / 60);
        int seconds = Mathf.FloorToInt(timer % 60);

        // Update the text element to display the current timer value
        timerText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
    }
}

In this script, we declare two variables: timerDuration and timer. timerDuration is a public variable that determines the duration of the countdown timer in seconds, while timer is a private variable that holds the current value of the timer.

It can be of Interest ;   Unity vs Unreal Engine 2023 | Which Engine Should You Use To Learn Game Dev

We also declare a public variable timerText, which is the text element that will display the countdown timer.

In the Start function, we initialize timer to the value of timerDuration.

In the Update function, we decrement timer by Time.deltaTime, which is the amount of time that has passed since the last frame. We also check if the timer has run out by comparing timer to zero. If the timer has run out, we set timer to zero and add code to handle the timer expiration.

Next, we convert the value of timer to minutes and seconds using Mathf.FloorToInt, which rounds down the float value to the nearest integer. We then update the text element timerText to display the current timer value using the string.Format function.

Note that this is just one example of how to implement a countdown timer in Unity using C# scripting. There are many ways to customize the timer to fit the needs of your game or application.

3. Adding the C# Script to the Text Element:

After writing the C# script for the countdown timer, the next step is to attach the script to the UI text element in the Unity editor. Here are the steps to do this:

  1. In the Unity editor, select the UI text element that was created in Step 2.
  2. In the Inspector window, scroll down to the “Text” component of the UI text element.
  3. In the “Text” component, click on the “+” button next to the “Components” section to add a new component.
  4. From the dropdown menu, select “New Script”.
  5. In the “Create New Script” dialog box, name the script “CountdownTimer” and select “CSharp” as the language.
  6. Click “Create and Add” to create the new script and add it to the text element.
  7. Double-click on the new “CountdownTimer” script to open it in the Unity editor.
  8. Copy and paste the C# code for the countdown timer from Step 3 into the new script.
  9. Save the script by pressing “Ctrl+S” on Windows or “Cmd+S” on Mac.
  10. In the Inspector window, make sure that the “CountdownTimer” script is selected and that the “Text” component is expanded.
  11. In the “Countdown Timer (Script)” section of the “CountdownTimer” script, there should be a field for “Text Object”. Drag the UI text element from the Hierarchy window into this field to connect the script to the text element.
  12. Finally, press the “Play” button in the Unity editor to test the countdown timer.

Here’s an example of what the code might look like in the CountdownTimer script:

    Adding the C# Script to the Text Element:

After writing the C# script for the countdown timer, the next step is to attach the script to the UI text element in the Unity editor. Here are the steps to do this:

    In the Unity editor, select the UI text element that was created in Step 2.

    In the Inspector window, scroll down to the "Text" component of the UI text element.

    In the "Text" component, click on the "+" button next to the "Components" section to add a new component.

    From the dropdown menu, select "New Script".

    In the "Create New Script" dialog box, name the script "CountdownTimer" and select "CSharp" as the language.

    Click "Create and Add" to create the new script and add it to the text element.

    Double-click on the new "CountdownTimer" script to open it in the Unity editor.

    Copy and paste the C# code for the countdown timer from Step 3 into the new script.

    Save the script by pressing "Ctrl+S" on Windows or "Cmd+S" on Mac.

    In the Inspector window, make sure that the "CountdownTimer" script is selected and that the "Text" component is expanded.

    In the "Countdown Timer (Script)" section of the "CountdownTimer" script, there should be a field for "Text Object". Drag the UI text element from the Hierarchy window into this field to connect the script to the text element.

    Finally, press the "Play" button in the Unity editor to test the countdown timer.

Note that this code assumes that the UI text element has been named “countdownText”. If the text element has a different name, you’ll need to modify the script accordingly.

It can be of Interest ;   1D Animation Blend Trees Explained (Unity Tutorial)

Once the script is attached to the text element and the game is running, the countdown timer should update in real-time based on the timeLeft variable in the script.

4. Testing the Countdown Timer

After creating the countdown timer and attaching the C# script to the UI text element, it’s important to test the timer to make sure it’s working properly. Here’s how to test the countdown timer in Unity:

  1. Click on the “Play” button in the Unity editor to enter play mode.
  2. Observe the timer in the game view to make sure it starts counting down from the correct value.
  3. If the timer is not starting at the correct value, adjust the “startingTime” variable in the C# script to the desired value. For example, if you want the timer to start at 2 minutes and 30 seconds, set the “startingTime” variable to 150 (2 minutes and 30 seconds in seconds).
  4. If the timer is counting down too quickly or too slowly, adjust the “countdownSpeed” variable in the C# script. The default value is 1, but you can increase or decrease it to speed up or slow down the countdown, respectively.
  5. If you want to change the duration of the countdown timer, simply adjust the “startingTime” variable in the C# script to the desired value.
  6. To stop the countdown timer, click on the “Stop” button in the Unity editor.

Here’s an example of the C# script used to control the countdown timer:

using UnityEngine;
using UnityEngine.UI;

public class CountdownTimer : MonoBehaviour
{
    public float startingTime = 120; // Starting time in seconds
    public float countdownSpeed = 1; // Speed at which the timer counts down

    private float currentTime; // Current time in seconds

    public Text countdownText; // UI text element that displays the countdown timer

    private void Start()
    {
        currentTime = startingTime;
    }

    private void Update()
    {
        currentTime -= countdownSpeed * Time.deltaTime;

        if (currentTime <= 0)
        {
            currentTime = 0;
            // Perform action when timer reaches zero
        }

        DisplayTime();
    }

    void DisplayTime()
    {
        float minutes = Mathf.FloorToInt(currentTime / 60);
        float seconds = Mathf.FloorToInt(currentTime % 60);

        countdownText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
    }
}

Note that this is just an example of a basic countdown timer script, and you may need to modify it to fit your specific needs.

5. Customizing the Countdown Timer

Once you have a basic countdown timer working in your game, you can customize it to fit your game’s style and theme. Here are some suggestions on how to modify the countdown timer:

  • Change the font, color, or position of the text element: You can customize the appearance of the countdown timer by changing the font, color, or position of the UI text element. For example, you could use a font that matches the style of your game, or use different colors to represent different levels of urgency. To change the position of the text element, you can use the RectTransform component in Unity to adjust the position, rotation, and scale of the element.
  • Add sound effects or animations to the timer: You can make the countdown timer more engaging by adding sound effects or animations to it. For example, you could play a ticking sound as the timer counts down, or have the text element shake or pulse to create a sense of urgency. To add sound effects, you can use Unity’s AudioSource component to play audio clips. To add animations, you can use Unity’s Animation or Animator components to create animations that play based on certain conditions, such as when the timer reaches zero.
  • Create a visual representation of the timer using graphics or shapes: Instead of using a text element to display the countdown timer, you could create a custom graphic or shape that represents the timer. For example, you could use a circular progress bar to show the remaining time, or use a series of colored blocks to represent different stages of the countdown. To create custom graphics or shapes, you can use Unity’s 2D or 3D graphics tools, such as the Sprite Editor or Mesh Editor.
It can be of Interest ;   Mastering Movement In Unity: Tips & Tricks

Here’s an example of how to change the font and color of the text element in the countdown timer:

// Set the font of the text element
textElement.font = Resources.Load<Font>("Fonts/MyCustomFont");

// Set the color of the text element
textElement.color = Color.red;

And here’s an example of how to add a ticking sound effect to the countdown timer:

// Add an AudioSource component to the text element
AudioSource audioSource = textElement.gameObject.AddComponent<AudioSource>();

// Load the ticking sound effect
AudioClip tickingClip = Resources.Load<AudioClip>("Audio/Ticking");

// Set the audio clip to play on loop
audioSource.clip = tickingClip;
audioSource.loop = true;

// Start playing the audio clip
audioSource.Play();

Note that these are just examples, and there are many ways to customize the countdown timer in Unity. The possibilities are limited only by your imagination and creativity!

Conclusion

In this article, we have shown you how to create a countdown timer in Unity using C# scripting. By following the step-by-step guide, you should now have a fully functional countdown timer that can be used in your games and applications.

To summarize, we started by creating a UI text element in the Unity editor, then wrote a C# script that controls the countdown timer’s behavior, such as updating the timer display, handling the timer’s start and end events, and providing customization options for the timer’s duration and starting value. We then attached the C# script to the text element, tested the countdown timer in Unity, and provided some suggestions on how to customize the timer for different types of games.

Here is the final version of the C# script that you can use as a reference or modify to fit your specific needs:

using UnityEngine;
using UnityEngine.UI;

public class CountdownTimer : MonoBehaviour
{
    public float totalTime = 60f;
    public Text timerText;

    private float timeRemaining;
    private bool timerIsRunning;

    private void Start()
    {
        timeRemaining = totalTime;
        timerIsRunning = true;
    }

    private void Update()
    {
        if (timerIsRunning)
        {
            if (timeRemaining > 0)
            {
                timeRemaining -= Time.deltaTime;
                DisplayTime(timeRemaining);
            }
            else
            {
                timeRemaining = 0;
                timerIsRunning = false;
                Debug.Log("Timer has ended!");
            }
        }
    }

    private void DisplayTime(float timeToDisplay)
    {
        float minutes = Mathf.FloorToInt(timeToDisplay / 60);
        float seconds = Mathf.FloorToInt(timeToDisplay % 60);

        timerText.text = string.Format("{0:00}:{1:00}", minutes, seconds);
    }
}

We hope this article has been helpful in your game development journey. With this knowledge, you can now add countdown timers to your games and applications, and create more engaging and interactive experiences for your users. Keep exploring Unity and C# to unlock even more possibilities!

If you want to see more interesting tutorials, don´t forget to come back to our blog.

4 Comments
  • JamesSluck says:
    Your comment is awaiting moderation. This is a preview; your comment will be visible after it has been approved.
    [url=https://www.ez-ddos.com/services.pl]взлом сайта на заказ[/url] – взлом сайта на заказ, ddos услуги
  • Jimmieenhaw says:
    Your comment is awaiting moderation. This is a preview; your comment will be visible after it has been approved.
    Господа!! У нас кондиционеры в авто заправляет не простой заправщик, а автоэлектрик с опытом более 8 лет работы по электрооборудованию автомобилей, потому не просто заправил и все, он проверяет всю систему и дается гарантия на услугу, выписывается чек, заказ-наряд Заправка,диагностика любых авто-кондиционеров на самом современном оборудование В Абакане,Саяногорске,Черногорске,Минусинске Уровень как у дилера!! База на все автомобили, все по граммам,сколько нужно-столько и заправим согласно заводскому регламенту на автомобиль!! Вы платите ровно столько,сколько заправляем в авто и не больше!! Так же МОЖЕМ ВЫКАЧАТЬ ВАШ ФРИОН С АВТОМОБИЛЯ НА ВРЕМЯ РЕМОНТА ПОТОМ ЗАПРАВИТЬ ЕГО ОБРАТНО!!! ВАМ НЕ НУЖНО БУДЕТ ЗА НЕГО ПЛАТИТЬ!! Вы платите ровно столько,сколько заправляем в авто и не больше!! г.Абакан ул.Вяткина 18 территория рембыттехники бокс 1 тел 8(3902) 320-456 тел 8-923-595-1234 [url=https://radikal.host/i/XZeZ3n][img]https://e.radikal.host/2023/05/08/photo_2023-04-08_20-41-20.md.jpg[/img][/url]
  • Tryptin-fum says:
    Your comment is awaiting moderation. This is a preview; your comment will be visible after it has been approved.
    I am not positive where you are getting your information, but good topic. I must spend a while finding out much more or figuring out more. Thank you for excellent info I was in search of this info for my mission.
  • 1 minute countdown says:
    Your comment is awaiting moderation. This is a preview; your comment will be visible after it has been approved.
    Hi, all the time i used to check weblog posts here early in the break of day, for the reason that i enjoy to find out more and more.
  • Leave a Reply

    Your email address will not be published. Required fields are marked *