Как сделать таймер в юнити
Перейти к содержимому

Как сделать таймер в юнити

  • автор:

 

How to add a Simple Countdown Timer in Unity

This post shows how to add a Simple Countdown Timer in Unity and also how you can use it for your own use-case depending on your application or game.

Also, learn how you can use the script to have a countdown timer to start a game in Unity. Follow simple and effective steps to add a countdown timer to your unity3D game or app.

Simple steps to follow.

Here is a simple tutorial to add a countdown timer in unity using a c# script.

  1. Create a C# Script called StartGame and copy the code from above and paste into it.
  2. Add this component to the Main Camera in the scene.
  3. Drag and drop the text component on to the script as shown in the image below.
    a. For example, You can drag and drop your text component, in this case, it is countdown as highlighted which will display the countdown text onto the Start Text section of the Start Game Script.
    b. We make the startText field public so that we can drag and drop the Text component directly onto the Start Game Script.
    c. You can also use this script to enable or disable GameObjects before and after the countdown. For example, in this game, I show the text “Tap to Fly” along with the Countdown text. Once the countdown is over, I disable the two text components and destroy them. You can also load a new game scene once the countdown is complete.

4. That’s it. You can now click the play button in unity to see the Countdown Timer in action.

For example, Here is a sample screenshot of a simple working example.

The above scripts and methods were successfully executed in Unity3D — Version 2017.3.0.

To conclude, this method and script are used in the development of Super Plane 2D game available in the Google play store.

Таймеры в Unity

Мне в одном классе нужно реализовать два таймера: первый бесконечно (или пока сцена с игрой не будет закрыто) должен каждые m секунд выполнять действие (1), второй каждые n секунд действие (2). Нужно учитывать то, что есть в игре пауза, и при её вызове нужно таймеры на паузу ставить (я бы мог сделать через корутины, но не знаю как их ставить на паузу). Как это можно реализовать?

Nikita Medvedev's user avatar

Самый банальный способ это иметь флаг, который устанавливается true/false когда игра активна/на паузе. В зависимости от этого флага уже танцевать в корутине.

Естественно isGameStopped скорее всего будет не в самом этом классе. Но это уже вам решать где его делать и в какой момент и каким способом его менять.

Смысл тут в том, что если флаг false , то будет простой банальный выход из корутины yield return null; . В ином же случае будет заход в if (!isGameStopped) и срабатывание счетчика.

Еще вариант — стартовать и останавливать корутину при возникновении какого-либо события (паузы)

В данном случае корутина запускается нажатием левой клавиши мыши, а останавливается нажатием на пробел. Но привязать это поведение к паузе, думаю сможете сами.

Создание простого таймера в Unity

Приветствую начинающих разработчиков игр. В данной статье мы научимся создавать простой таймер, который будет иметь функции старта, паузы, и остановки таймера. Управляться таймер будет в ручном режиме, с помощью соответствующих кнопок.

Для начала создадим три кнопки с помощью окна Hierarchy, выбрав UI — Button — TextMeshPro. Так же создадим и текстовое поле, в котором будет отображаться время нашего таймера: UI — Text — TextMeshPro.

Текст для трёх кнопок укажем следующий: "Старт", "Пауза", "Стоп". А для текстового поля просто укажем 0. Выглядеть это будет примерно так:

Чтобы наши кнопки умели запускать и останавливать таймер, необходимо для них написать соответствующие функции. Для этого с помощью окна Project создадим C# скрипт, и дадим ему название, например, Timer. Этот скрипт присвойте любому игровому объекту, например вашей камере, или канвасу.

Содержание данного скрипта следующее:

Обратите внимание, что во второй строчке мы подключили TMPro, поскольку мы работаем с UI элементами типа TMPro.

В строке #6-8 мы объявили три переменные:

  • time хранит время самого таймера.
  • start — хранит информацию о том, запущен ли таймер или остановлен.
  • value — хранит ссылку на UI элемент Text — TextMeshPro. Не забудьте перетащить данный объект из окна Hierarchy в поле value скрипта Timer, окна Inspector.

Далее мы создали три функции для наших кнопок:

  • StartTimer() — функция для запуска таймера.
  • PauseTimer() — функция для паузы таймера.
  • StopTimer() — функция для полной остановки таймера, и сбрасывания значение таймера до нуля.

Ну и в функции Update() мы проверяем, если таймер запущен, то увеличиваем значение time, и выводим это значение на экран, предварительно преобразовав числовое значение time в строковое, с помощью метода ToString.

Вся основная работа сделана. Осталось прикрепить к нашим кнопкам, наши функции из скрипта. Для этого сделаем 2 простых действия:

  • Нажмём на нашу кнопку с текстом "Старт", и в инспекторе в поле On Click() перетащим наш объект, на котором имеется наш скрипт Timer. В моём случаем это объект Canvas.
  • Нажмём на No Function, и выберем там Timer — StartTimer().

Такие же действия проделаем и с кнопками "Пауза" и "Стоп", присвоив им оставшиеся функции: Timer — PauseTimer() и Timer — StopTimer().

 

Таймер готов! Данный таймер можно переделать таким образом, чтобы он работал не на увеличение значения таймера, а на уменьшение. Принцип такого таймера впринципе такой же.

Если Вам данная статья была полезна, буду рад вашим лайкам и комментариям 🙂

Unity timer tutorial: Creating Countdown timer with C# script

Looking to create a Countdown timer with seconds and minutes functionality? Then this is the tutorial for you. We will also see how to set up the UI required for displaying a countdown timer in Unity and how to display the time in minutes and seconds.

If you are looking to create a simple delay then you can use Unity Coroutine or the Async await functions. If you are looking to make a stopwatch then check out our tutorial on Unity stopwatch.

The codes have been tested in Unity editor and the output is displayed for your reference.

Unity Timer terminologies you should know

    – Intervals between frames. – Interval between physics frames. – this is the time passed from the start of the game. – time passed from the start of the game to the recent fixed update. – the speed at which time passes in your game.

Creating a countdown timer In Unity

  • Copy and paste the code above to your script.
  • Add a new Text UI to your scene by going to Create>UI>Text and name it as Timer Display.
  • Adjust the font size to your requirement.
  • Drag and drop the Timer Display gameobject to the text variable (Disvar) in the timer gameobject.
  • Play the game and you should see the timer working.

Tip: Always initialize your private variables in the Start function and not the awake function. You can read the difference between them in our Unity Awake vs Start post.

Completed message displayed after Unity timer value less than 0

Using a Text mesh pro text UI for Timer display

The new version of Unity has moved the text UI in the legacy menu and will slowly remove the support for it.

adding TMP text UI in Unity

If you add a Text mesh pro UI text to your scene you need to make the following changes to the script.

  1. Change “using UnityEngine.UI” to “using TMPro”
  2. The data type of the text element will be TMP_Text.

Rest of the procedure and code will remain same. Here is how the final script will look like if you are using text mesh pro.

Displaying time in Minutes and seconds

In our above examples the timers are displayed in decimal format but the actual time should be displayed in Minutes:Seconds

Unity timer in Minutes:Seconds format

We need to add two more Text UI to our scene. One will be for minutes and the other will be for seconds.

You can name them minutes and seconds.

Now let’s go back to the script and add two more public text variables.

In case of Text mesh pro the data type will be TMP_Text.

Mathf has a function called FloortoInt which we can use to get the minutes and seconds.

Then we can assign those values to the text variables.

Unity timer C# script with Seconds and minutes display

Using String Format to display time in Minutes and seconds

You can display the Minutes and Seconds in a Single text UI using a String format. Here is a code sample

The way string formatting works is by inserting the values inside the curly braces <> which are inbetween the string. Inside the <> the first value is the index of the variable starting from 0 and the second is the format of the variable.

General syntax of the string format looks like this

String format explained in C#

Getting time elapsed in your Countdown timer

You can either count up from zero to get the time elapsed or you can subtract the current value of the countdown variable with the starting value to get the time elapsed.

Subtracting from the initial value

If you have any other questions on Unity timer, feel free to leave it in the comment below. If you like the article share it with your friends.

 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *