• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
Question by CarlLawl · Feb 01, 2011 at 06:21 PM · timersecondsminutes

making a timer (00:00) minutes and seconds

Ok, so Im trying to make a game timer that increments every second and displays it in the format of MM:SS

Heres what I have

 public static float timer;
 public static bool timeStarted = false;
 
 void Update ()
  {
     if (timeStarted == true) 
    {
         timer += Time.deltaTime;
     }       
 }
 
 void OnGUI()
  {
     float minutes = Mathf.Floor(timer / 60);
     float seconds = timer%60;
 
     GUI.Label(new Rect(10,10,250,100), minutes + ":" + Mathf.RoundToInt(seconds));
 }


but it outputs M:S (if the seconds is over 10 then obviously the seconds will be double digit) would anyone be able to explain where im going wrong?

Comment
burnumd
TooManySugar
EmmanuelMess
alxcancado
MPHYS
Edisyo
Dalsia
pciechowicz
lagzilajcsi
EDevJogos
13goat

People who like this

11 Show 0
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

10 Replies

· Add your reply
  • Sort: 
avatar image
Best Answer

Answer by LoTekK · Feb 01, 2011 at 06:40 PM

I would imagine there's a cleaner way to do this, but:

 float minutes = Mathf.Floor(timer / 60);
 float seconds = Mathf.RoundToInt(timer%60);
 
 if(minutes < 10) {
     minutes = "0" + minutes.ToString();
 }
 if(seconds < 10) {
     seconds = "0" + Mathf.RoundToInt(seconds).ToString();
 }
 GUI.Label(new Rect(10,10,250,100), minutes + ":" + seconds);

Here I'm just converting the float to a string if the value is less than 10, and sticking a leading zero on. Also, performing the RoundToInt at the variable definition instead of in the GUI.Label call. Haven't had time to actually test it, but that should work.

Comment
LastTemplar
Rxanadu
atifmahmood29
DDMiller
J_moke
Enyph-Games
winwin0108
kriptite
Dhaval1992
Black_Demon
alxcancado
gbelini
EddyDavila
Gng357
zeimhall
And 7 more...

People who like this

20 Show 6 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image asafsitner · May 20, 2012 at 11:32 AM 9
Share

The cleaner way of doing it is use the built-in option for custom `ToString()` formats as such:

 float minutes = Mathf.Floor(timer / 60).ToString("00");
 float seconds = (timer % 60).ToString("00);

This will force the number to always display at least two-digits even when their value is lower than 10, replacing the first digit with a 0. When using the similar format of "#0" the first digit will only show if the number's value is greater than or equal to 10.

avatar image ismaelnascimento01 asafsitner · May 11, 2018 at 04:16 AM 2
Share

Right...:

 void Update(){
    float timer += Time.deltaTime;
 
     string minutes = Mathf.Floor(timer / 60).ToString("00");
     string seconds = (timer % 60).ToString("00");
     
     print(string.Format("{0}:{1}", minutes, seconds));
 }

avatar image raptorkwok · Feb 21, 2014 at 02:44 AM 0
Share

You can't cast float to string. Codes don't compile at all.

avatar image raphik12 · May 27, 2014 at 04:26 PM 1
Share

That's what asafsitner wanted to type:

 string minutes = Mathf.Floor(timer / 60).ToString("00");
 string seconds = (timer % 60).ToString("00");
avatar image bbharier · Sep 02, 2014 at 01:40 AM 7
Share

You'll want to add a Mathf.Floor to the seconds as well, if to prevent a display bug where you see 00:60 for half a second. (It rounds the displayed seconds up to 60 from 59.9999 - 59.5)

 string minutes = Mathf.Floor(timer / 60).ToString("00");
 string seconds = Mathf.Floor(timer % 60).ToString("00");


avatar image zero3growlithe · Jan 04, 2015 at 03:24 PM 9
Share

I have a method in C# that has some code formattings implemented if anyone will find it useful:

 public string FloatToTime (float toConvert, string format){
         switch (format){
             case "00.0":
                 return string.Format("{0:00}:{1:0}", 
                     Mathf.Floor(toConvert) % 60,//seconds
                     Mathf.Floor((toConvert*10) % 10));//miliseconds
             break;
             case "#0.0":
                 return string.Format("{0:#0}:{1:0}", 
                     Mathf.Floor(toConvert) % 60,//seconds
                     Mathf.Floor((toConvert*10) % 10));//miliseconds
             break;
             case "00.00":
                 return string.Format("{0:00}:{1:00}", 
                     Mathf.Floor(toConvert) % 60,//seconds
                     Mathf.Floor((toConvert*100) % 100));//miliseconds
             break;
             case "00.000":
                 return string.Format("{0:00}:{1:000}", 
                     Mathf.Floor(toConvert) % 60,//seconds
                     Mathf.Floor((toConvert*1000) % 1000));//miliseconds
             break;
             case "#00.000":
                 return string.Format("{0:#00}:{1:000}", 
                     Mathf.Floor(toConvert) % 60,//seconds
                     Mathf.Floor((toConvert*1000) % 1000));//miliseconds
             break;
             case "#0:00":
                 return string.Format("{0:#0}:{1:00}",
                     Mathf.Floor(toConvert / 60),//minutes
                     Mathf.Floor(toConvert) % 60);//seconds
             break;
             case "#00:00":
                 return string.Format("{0:#00}:{1:00}", 
                     Mathf.Floor(toConvert / 60),//minutes
                     Mathf.Floor(toConvert) % 60);//seconds
             break;
             case "0:00.0":
                 return string.Format("{0:0}:{1:00}.{2:0}",
                     Mathf.Floor(toConvert / 60),//minutes
                     Mathf.Floor(toConvert) % 60,//seconds
                     Mathf.Floor((toConvert*10) % 10));//miliseconds
             break;
             case "#0:00.0":
                 return string.Format("{0:#0}:{1:00}.{2:0}",
                     Mathf.Floor(toConvert / 60),//minutes
                     Mathf.Floor(toConvert) % 60,//seconds
                     Mathf.Floor((toConvert*10) % 10));//miliseconds
             break;
             case "0:00.00":
                 return string.Format("{0:0}:{1:00}.{2:00}",
                     Mathf.Floor(toConvert / 60),//minutes
                     Mathf.Floor(toConvert) % 60,//seconds
                     Mathf.Floor((toConvert*100) % 100));//miliseconds
             break;
             case "#0:00.00":
                 return string.Format("{0:#0}:{1:00}.{2:00}",
                     Mathf.Floor(toConvert / 60),//minutes
                     Mathf.Floor(toConvert) % 60,//seconds
                     Mathf.Floor((toConvert*100) % 100));//miliseconds
             break;
             case "0:00.000":
                 return string.Format("{0:0}:{1:00}.{2:000}",
                     Mathf.Floor(toConvert / 60),//minutes
                     Mathf.Floor(toConvert) % 60,//seconds
                     Mathf.Floor((toConvert*1000) % 1000));//miliseconds
             break;
             case "#0:00.000":
                 return string.Format("{0:#0}:{1:00}.{2:000}",
                     Mathf.Floor(toConvert / 60),//minutes
                     Mathf.Floor(toConvert) % 60,//seconds
                     Mathf.Floor((toConvert*1000) % 1000));//miliseconds
             break;
         }
         return "error";
     }
avatar image

Answer by jashan · Sep 08, 2012 at 06:45 PM

Actually, there's a much nicer way of doing this:

 void OnGUI() {
     int minutes = Mathf.FloorToInt(timer / 60F);
     int seconds = Mathf.FloorToInt(timer - minutes * 60);

     string niceTime = string.Format("{0:0}:{1:00}", minutes, seconds);
 
     GUI.Label(new Rect(10,10,250,100), niceTime);
 }

This will give you times in the 0:00 format. If you'd rather have 00:00, simply do

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

There's a couple of possibilities you have with the formats here: {0:#.00} would give you something like 3.00 or 10.12 or 123.45. For stuff like scores, you might want something like {0:00000} which would give you 00001 or 02523 or 20000 (or 2000000 if that's your score ;-) ). Basically, the formatting part allows any kind of formatting (so you can also use this to format date times and other complex types). Basically, this means {indexOfParameter:formatting}.

Comment
save
Stardog
raptorkwok
flamy
eelstork
andre-ivankio
BillHill
Pariah Silver
daviddickball
StabbingBogan
TooManySugar
Animatick
nickthegreek
RChrispy
Phoxxer
And 49 more...

People who like this

62 Show 8 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image StabbingBogan · Jul 24, 2015 at 06:13 AM 0
Share

Works beautifully. Thankyou

avatar image Animatick · Sep 01, 2015 at 05:53 AM 0
Share

i have to say thank you .....ive been working on this problem for days going crazy and this solution works great i was jumping up and down for join when i saw it working....thank you

avatar image Eco-Editor · Jun 20, 2017 at 11:50 AM 0
Share

Hi @jashan Where should I place this script? I use steamVR, and placing it on the cameraRig- eyes will not worl for me.

avatar image devilb2103 · Nov 20, 2020 at 04:07 PM 0
Share

Wow this works great, but when I reload the scene it doesn't reset. Any idea why?

avatar image Xain devilb2103 · Nov 20, 2020 at 05:28 PM 0
Share

maybe you have static script?

avatar image unity_AmSezFmN7VbhDQ · Nov 07, 2021 at 12:45 PM 0
Share
 string niceTime = string.Format("{0:00}:{1:00}", minutes, seconds);

It says that minutes and seconds don't exist in the context, do I still need to add the int minutes part? I thought it declared it in that but I could be wrong

Show more comments
avatar image

Answer by YasinJavaid_ · Jul 15, 2016 at 11:15 AM

sorry guys its late but single line solution is here

 (totalTimeSec / 60 ).ToString("00")  + ":" + (totalTimeSec%60).ToString("00");

 or 
 
 Mathf.Floor(totalTimeSec / 60 ).ToString("00")  + ":" + Mathf.FloorToInt(totalTimeSec%60).ToString("00");
 

try 2nd solution.

Comment
Vels
m0guz
Sanky
Babul2
Babul23
Azurne
rbernalandreo
YasinDev
mkusan
DamDamDuSixZero
sacredgeometry
yasinjavaid
Ozi-Saqib
YasinSablo
$$anonymous$$
And 3 more...

People who like this

16 Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image rbernalandreo · Aug 30, 2018 at 09:52 AM 0
Share

You forgot the Mathf.Floor (With 31 seconds, with your solutions shows 01:31)

 Mathf.Floor(totalTimeSec / 60 ).ToString("00")  + ":" + Mathf.FloorToInt(totalTimeSec%60).ToString("00");


avatar image YasinJavaid_ · Oct 15, 2019 at 05:20 AM 0
Share

Thanks for mentioning added to answer

avatar image

Answer by Stardog · Jun 02, 2013 at 10:49 AM

Here is the example burnumd mentioned:

 public float timer;
 public string timerFormatted;

 void Update()
 {
     System.TimeSpan t = System.TimeSpan.FromSeconds(timer);

     timerFormatted = string.Format("{0:D2}h:{1:D2}m:{2:D2}s:{3:D3}ms", t.Hours, t.Minutes, t.Seconds, t.Milliseconds);
 }
Comment
AbgaryanFX
vagalume
Adam-Buckner
sabari_2
VonTala
EmmanuelMess
Axtrainz
m0guz
Black_Demon
kalamtech
Ali_V_Quest
sacredgeometry
Luis0413

People who like this

13 Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image BMayne · Sep 02, 2014 at 02:55 AM 0
Share

Hey Stardog,

You can just go t.ToString("hh:mm:ss:fffffff");

Regards,

avatar image

Answer by burnumd · Feb 01, 2011 at 07:32 PM

Look into using C#'s string.Format. I'd recommend looking at this StackOverflow exchange which explains using it to display a time however you want it using a TimeSpan which you can create by calling new System.TimeSpan.FromSeconds (timer).

Comment
AbgaryanFX
vagalume
sacredgeometry

People who like this

3 Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image CarlLawl · Feb 03, 2011 at 04:38 PM 0
Share

i thought string.Format was js only because when i tried typing it in c# in monodev it was throwing up error, any reason why? ive check out that link though thanks!

avatar image burnumd · Feb 03, 2011 at 06:20 PM 0
Share

There could be lots of reasons why it threw up an error. Can you tell me what error you're getting?

  • 1
  • 2
  • ›

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

29 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Turn seconds into minutes and seconds MM:SS 1 Answer

How to stop a Countdown Timer? 1 Answer

Countdown Timer Help About putting 0's 1 Answer

Making a timer 1 Answer

Referencing other scripts: -5 seconds rule on timer 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges