How to make a Countdown Timer in Unity (in minutes + seconds)

Поділитися
Вставка
  • Опубліковано 8 вер 2024

КОМЕНТАРІ • 87

  • @brookefeely3684
    @brookefeely3684 Рік тому +10

    If anyone's having problems with the Text not connecting at the end (when dragging into the Timer Text slot), it may be because of TextMeshPro.
    At the top of the code, add
    using TMPro;
    Then in the public float section change "public Text timeText;" to:
    public TextMeshProUGUI timeText;
    Now you should be able to attach the TextMesh :)

    • @brookefeely3684
      @brookefeely3684 Рік тому

      (PS Thank you GDB for this, this was so helpful!)

    • @fionaoncedargrove6121
      @fionaoncedargrove6121 Рік тому +1

      i love you

    • @brookefeely3684
      @brookefeely3684 Рік тому

      @@fionaoncedargrove6121 I spent a horrific amount of time trawling different kinds of issues to find out why 🥲 I wish Unity would put info like that about version updates in the API.

  • @bloomyfractal3585
    @bloomyfractal3585 3 роки тому +38

    FULL SCRIPT:
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    public class Timer: MonoBehaviour
    {
    public float timeValue = 90;
    public Text timerText;
    //Update is called once per frame
    void Update()
    {
    if (timeValue > 0)
    {
    timeValue -= Time.deltaTime;
    }
    else
    {
    timeValue = 0;
    }
    DisplayTime(timeValue);
    }
    void DisplayTime(float timeToDisplay)
    {
    if (timeToDisplay < 0)
    {
    timeToDisplay = 0;
    }
    float minutes = Mathf.FloorToInt(timeToDisplay / 60);
    float seconds = Mathf.FloorToInt(timeToDisplay % 60);
    float milliseconds = timeToDisplay % 1 * 1000;
    timerText.text = string.Format("{0:00}:{1:00}:{2:000}", minutes, seconds, milliseconds);
    }
    }

  • @zaimamukhtar6633
    @zaimamukhtar6633 Рік тому +1

    the most efficient working video on youtube I found after 2 hours of search

  • @AleySoundz
    @AleySoundz 2 роки тому +1

    This tutorial is amazing. I needed a repeating timer and this is super simple and does exactly what I need.

  • @booblock9550
    @booblock9550 3 роки тому

    spent hours on the internet and discord trying to find how to do this but apparently no one knows but youtubers. thanks much.

  • @lennyseed9255
    @lennyseed9255 3 роки тому +1

    This tutorial just saved my timed game. Thanks alot

  • @achraf844
    @achraf844 Рік тому +1

    hope you blow up in subscription count , came to like your videos cause of the timer countdown article , your content is clean , and your work worth more than you get , Thank you !

  • @ericbaum5759
    @ericbaum5759 3 роки тому +2

    Awesome tutorial and blog article. Thank you!

  • @jamesbishop4183
    @jamesbishop4183 11 місяців тому

    Awesome tutorial man. Thank you

  • @4everNFS
    @4everNFS 2 місяці тому +1

    Hey, awesome tutorial, worked the first time around. One question, how to make it so that it pauses the timer/resets the timer? I have 2 buttons in my app and I need them to pause or reset the timer

  • @mintydog06
    @mintydog06 3 роки тому +1

    An excellent turotial, thank you.

  • @JacobS-rh7tb
    @JacobS-rh7tb 3 роки тому +4

    Outstanding tutorial!!
    Quick question: what theme are you using for your VS? It looks great!

  • @jasonkane7231
    @jasonkane7231 2 роки тому

    This is a great tutorial. Simple, fast, to the point! I'll definitely check more of your videos in the future. The way you easily explain code step-by-step reminds me of Brackeys, who've sadly stopped doing videos.

    • @kartman146
      @kartman146 2 роки тому

      So what you're trying to say, is that he should become the next Brackeys

  • @lovfall642
    @lovfall642 Рік тому

    Thank you so much!

  • @tejasbele1456
    @tejasbele1456 2 роки тому

    Wow!!!! This video helped me a lot. You are really awesome. Keep doing this and you will be the greatest youtuber for Game Dev Videos.

  • @lordcusnir
    @lordcusnir 3 роки тому +1

    What a legend! Tank you so much!

  • @DaringGamerYT
    @DaringGamerYT 2 роки тому +3

    Quick Q: What if you want to just show it in seconds? Which part of the script would need to be removed? Also does it run if you exit out of the app (supposing the timer is in an app)

  • @m-studios4028
    @m-studios4028 2 роки тому +1

    Great tutorial. Well explained.
    Keep the good work. Good Luck!

  • @pimpermax5176
    @pimpermax5176 Рік тому

    this was amazing!

  • @potatoml4631
    @potatoml4631 2 роки тому

    thanks for the very usefull tutorial, as beginner in unity3d and programming im looking forward for new videos from you

  • @garretxgarret
    @garretxgarret Рік тому

    Great tutorial! Thanks for the help.

  • @dougstewart107
    @dougstewart107 2 роки тому

    Very well explained, thank you very much for the tutorial.

  • @TheLazyIndianTechie
    @TheLazyIndianTechie 2 роки тому +1

    Great tutorial. How do you persist time across scenes though?

  • @jacqueyotsuba6058
    @jacqueyotsuba6058 3 роки тому +1

    Really helpful, thanks so much!

  • @PatryEchelon
    @PatryEchelon 3 роки тому

    Super helpful!! Thank you so much for sharing

  • @jimmybob981
    @jimmybob981 3 роки тому +2

    Great tutorial and article! Really random question but new to coding, what was the hotkey you used at 2:05 to automatically add brackets around the timeValue line? Seems pretty useful.
    Ah, additional question after doing some fiddling, if I set the time to just using minutes/seconds with seconds just as timeToDisplay, the timer seems to start at 90:960. Although just changing the start value to 89 is a hacky way to fix that is that just an issue with how the milliseconds are being calculated?

  • @lawrencekoestler742
    @lawrencekoestler742 3 роки тому

    Your a good teacher. Very well explained. Thanks p.s. MAKE MORE!

  • @ThePokeChannel1
    @ThePokeChannel1 3 роки тому

    This helped out so much thank you man!

  • @alejandrozamora3468
    @alejandrozamora3468 2 роки тому

    This is awesome mate. Really appreciate the help.

  • @jakubjakubowski830
    @jakubjakubowski830 2 роки тому

    Great tutorial

  • @codojunior
    @codojunior 3 роки тому +3

    How do I make the timer stop when I hit a box collider, like for example in a maze game when you get to the princess and you win the game, that's when I want the timer to stop and if you don't get to the princess in time, you loose and you have to start the level again?

    • @supernova1860
      @supernova1860 3 роки тому

      I have mine set up as a gameobject that another script can reference and simply turn off once the player is inside the collision the script attached has.
      if (other.gameObject.CompareTag ("Player"))
      {
      timerCountdown.GetComponent().enabled = false;
      }

  • @mr.shellbee
    @mr.shellbee 2 роки тому

    Thank you very much

  • @asmitatirkey9294
    @asmitatirkey9294 3 роки тому

    Thank YOU

  • @simpsonelli
    @simpsonelli 3 роки тому

    Great tutorial, thanks

  • @OniGameDev
    @OniGameDev 2 роки тому

    Thanks!

  • @nikunjbaraiya8555
    @nikunjbaraiya8555 2 роки тому

    thanks a lot bro

  • @carlosrd9901
    @carlosrd9901 3 роки тому

    great video! please make more :)

  • @ThePokeChannel1
    @ThePokeChannel1 3 роки тому +1

    Is there a way to start the timer on a Key Press in runtime?

  • @zaidalfayyadh_2537
    @zaidalfayyadh_2537 Рік тому

    Great tutorial!! subscribe.

  • @random_precision_software
    @random_precision_software Рік тому

    Im looking for a timer the number are halfed in the middle and the top half falss down to show the next number (Like the ones seen in OLD TRAIN STATIONS) you know what i mean ?

  • @leoisforevercool
    @leoisforevercool 2 роки тому +1

    I can't drag my text onto the TimerText box in the inspector, it changes my mouse to the crossed out circle.
    Any idea why or what to do here?
    I'm tearing my hair out trying to fix it

    • @MrGameguyC
      @MrGameguyC 2 роки тому

      Are you using Text - TextMeshPro?
      Cause that won't work.
      Use Text in the Legacy tab also located in UI, that will work.

    • @leoisforevercool
      @leoisforevercool 2 роки тому

      @@MrGameguyC Hey man it's all good I hired someone to start scripting for me haha

    • @MrGameguyC
      @MrGameguyC 2 роки тому

      @@leoisforevercool Sweet, glad to hear!

  • @marcosssocram
    @marcosssocram 3 роки тому

    Where can I get that font? Great tutotial, btw, the article is also really well writen. :D

    • @marcosssocram
      @marcosssocram 3 роки тому

      Found it, is at the bottom of the article :P

  • @amirabarham1515
    @amirabarham1515 3 роки тому

    You are awesome

  • @drnado863
    @drnado863 3 роки тому

    does this format you used also work if i have 10 minutes? if so do i have to change something?

  • @phutrancong2810
    @phutrancong2810 Рік тому

    this is my way if any one want to use it outside Update:
    private IEnumerator startCountDown()
    {
    while (currentLimit > 0)
    {
    --currentLimit;
    UpdateLimitText();
    yield return new WaitForSeconds(1.0f);
    }
    }
    private void UpdateLimitText()
    {
    var timeSpan = TimeSpan.FromSeconds(currentLimit);
    timerText.text = string.Format("{0:D1}:{1:D2}", timeSpan.Minutes, timeSpan.Seconds);
    }

  • @sweetsfromcandys2847
    @sweetsfromcandys2847 2 роки тому

    Hello there, great tutorial, it works perfect, one question can you please show how to put it in to mili seconds, i have tried for a while now and im finding it to be impossible lol:):):)

    • @sweetsfromcandys2847
      @sweetsfromcandys2847 2 роки тому

      I just found your article and the answer to my question was sitting right there, i was at this for like 5 hours lol, id just like to say, a very well structure article and very easy to understand, so thank you very much:):):)

  • @gameswithfrank
    @gameswithfrank 2 роки тому +2

    doesnt he sound like mark from gmtk?

  • @EseRooster
    @EseRooster Рік тому

    Great script, but I wonder how to convince Unity to read time from timeValue, not from Unity inspector. I want to make different levels, depending on timeleft, but cannot do it cause this overwriting value in Unity. Would someone have any tips for that?

  • @dkordy
    @dkordy 2 роки тому

    The video is perfect, a perfect explanation. Great ... But I need help and I can't find it anywhere! on the whole You tube! And help is about countdowntime - -how do I stop the countdown when I want to? for example: I have a player and he has to complete a task until time runs out. My countdown timer works great and if the player doesn't complete the task until the time runs out I made it appear to me -time has expired /panel---but the problem arises if in the meantime that player hits an object (bomb) before time runs out I made it appear to me - the game is over-panel- and time continues to count down and when it counts down to the end it appears -time is expired /panel to. How do I stop that countdown, for example, when my game is over/ panel is up? how in code to make void to stop countdown? can you please,please help me! I can't find the answer on the whole youtube, everyone is making a video about how to countdown or add time and no one is talking about how to stop that countdown if you need it!Please,I turned to you because you presented yourself as a person who is ready to help and guide you to the right answers! so please,please help!

  • @panendraommina3474
    @panendraommina3474 3 роки тому +3

    How do you make the seconds timer from 00 to 59 ( still wondering )

    • @tughanalpaslan
      @tughanalpaslan 3 роки тому

      Hello, like this
      DisplayTime(UpgradeTimer - CurrentUpgradeTimer);

  • @roboticol6280
    @roboticol6280 3 роки тому +1

    we can also use coroutines right?

  • @Wilkoooo
    @Wilkoooo 2 роки тому

    Does anyone know how you could do this with a visual bar instead of text?

  • @patek2385
    @patek2385 3 роки тому

    What should I add to this If I want to set the game over screen when counter reaches 0?

    • @jimmybob981
      @jimmybob981 3 роки тому +3

      if(timeToDisplay < 0)
      {
      timeToDisplay = 0;
      SceneManager.LoadScene(_GameOver);
      }
      And then at the top put a:
      using UnityEngine.SceneManagement;
      Along with the other Unity system calls and a:
      [SerializeField] string _GameOver;
      So that in Unity, you should have an editable field to enter the Scene name for your game over screen.

    • @patek2385
      @patek2385 3 роки тому

      @@jimmybob981 Thank You bro, I will try it later.

    • @adambouches7396
      @adambouches7396 3 роки тому

      @@jimmybob981 are you saying in serializefield inside unity I should drag the game over scene and place it in that field

  • @HienNguyen-cs1md
    @HienNguyen-cs1md Рік тому

    It doesn't work with TextMeshPro, can anyone help me with this.

  • @Aschended
    @Aschended 3 роки тому

    can you add something to collect like money when the countdown end?

    • @SrCapricorno
      @SrCapricorno 3 роки тому

      you can add below or above the timeToDisplay = 0,
      but you'll need to reference your money script,
      ex: if(timeToDisplay < 0)
      {
      timeToDisplay = 0;
      money.AddMoney(100);
      In your money script, create a public void AddMoney(int money)
      then you can add by others scripts how much you want to add in your money script

    • @Aschended
      @Aschended 3 роки тому

      @@SrCapricorno actually i have somekind of project with my friend and thats to make something when player(make item), it will need to first to choose how many items to make then "enter", from your code we already try it, it will make endlessly collect money, need to stoping collect money when the timer stop too, can you help with that?

    • @SrCapricorno
      @SrCapricorno 3 роки тому +1

      @@Aschended try this:
      int money;
      public void AddMoney()
      {
      money += 1;
      }
      To every task complete, reference this from others scripts:
      Ex:
      public moneyScript money;
      When task is complete:
      money.AddMoney();

    • @Aschended
      @Aschended 3 роки тому +1

      @@SrCapricorno let me try it first i not sure if i can make it but will give you a replay if it work.
      P.s sry for my bad english and thank you for replaying.

    • @SrCapricorno
      @SrCapricorno 3 роки тому

      @@Aschended you're welcome, you can message me when you need, I'll be here, hope i can help you

  • @dingolt6021
    @dingolt6021 2 роки тому

    how do i add milliseconds?

  • @charlieindge1751
    @charlieindge1751 3 роки тому

    Timer.cs(32,25): error CS0103: The name 'MathF' does not exist in the current context
    Any ideas??

    • @charlieindge1751
      @charlieindge1751 3 роки тому +1

      Figured this issue out:
      Instead of using float minutes = MathF.FloorToInt (timeToDisplay / 60);
      float seconds = MathF.FloorToInt(timeToDisplay % 60);
      just use float minutes = (timeToDisplay / 60);
      float seconds = (timeToDisplay % 60);
      it works exactly the same, ive had zero issues with this.

  • @twaaan
    @twaaan 2 роки тому

    Does anybody know why the text doesn't change? I can see that the timer is working since is counting down the seconds, but the text is changing and is stuck on 00:00. Can anyone halp me?

    • @twaaan
      @twaaan 2 роки тому

      *is not changing

    • @jimdeveloping
      @jimdeveloping 2 роки тому

      did you check the inequalities signs? if they are the wrong way, that could cause the issue.

  • @skullydev5710
    @skullydev5710 2 роки тому

    why cant I drag the Text to the TimerText :(

    • @haydenwright1683
      @haydenwright1683 Рік тому

      Are you using TextMeshPro (TMP)? If so you will need to use using TMPro; in place of using UnityEngine.UI;
      You will also need to change public Text TimerText; to TMP_Text timerText;

    • @bertolamaiana1144
      @bertolamaiana1144 Рік тому

      @@haydenwright1683 I have the same issue and I follow your steps; but still I cannot drag the text to TimerText 😿
      using System.Collections;
      using System.Collections.Generic;
      using UnityEngine;
      using TMPro;
      public class Timer : MonoBehaviour
      {
      //time
      public float timeValue = 60;
      public TMP_Text timerText;
      //gamemanager
      private GameManager gameManager;
      // Start is called before the first frame update
      void Start()
      {
      gameManager = GameObject.Find("Game Manager").GetComponent();
      }
      // Update is called once per frame
      void Update()
      {
      if (timeValue > 0)
      {
      timeValue -= Time.deltaTime;
      }
      else
      {
      timeValue += 0;
      gameManager.isGameActive = false;
      }
      DisplayTime(timeValue);
      }
      void DisplayTime(float timeToDisplay)
      {
      if (timeToDisplay < 0)
      {
      timeToDisplay = 0;
      }
      float minutes = Mathf.FloorToInt(timeToDisplay / 60);
      float seconds = Mathf.FloorToInt(timeToDisplay % 60); // time modulo 60 => I get
      timeText.text = string.Format("{00:00}:{1:00}", minutes, seconds);
      }
      }

  • @DeusLucifer
    @DeusLucifer 2 роки тому

    how do people study and remember all the codes needed to make lots of things i don't understand

  • @lucas1minuto
    @lucas1minuto 3 роки тому

    Thank you very much 👍