Unity3D: Convert Seconds to hh:mm:ss Format

Update 17.8.2021: Replaced obsolete Monodevelop with Visual Studio where applicable. 

I have gradually started to use Unity3D for game development. So far I have been doing very small and simple test codes just to learn how certain things should be done with Unity.

But now I have an example that might be of interest for other wannabe-Unity3D users, at least those who are struggling with converting seconds to HH:MM:SS format. :) So lets begin with this example.

First of all, start Unity3D and create new project. This example uses the console only for outputting result, so project can be either 2D or 3D. Whichever you prefer.

Create empty object to your scene (ctrl+shift+N), or use pulldown menu (GameObject->Create Empty).

Select empty object and rename it e.g. to "Timer". Add new C# script component to empty object and name it as "TimerActions" (Add Component->New Script->write name and select Csharp as script type):

Open TimerActions script to your favorite editor (double click "TimerActions" thumbnail in Assets folder). I am using Visual Studio for editing Unity scripts, but I guess any other decent editor will also do fine.

Write C# script as follows (or get it from GitHub):

The basic idea of script is to measure time using so called deltaTime, that is time taken to complete the last frame. Execution time between consecutive frames may differ significanty depending on what kind of processing your app is doing. So using deltaTime makes ýour app to run precisely, no matter what framerate is.

TimeCounter variable contains the time in seconds. To extract hours, minutes and seconds information from that we have to do some calculations:

  • Hours are calculated by dividing seconds with 3600, and then rounding the result down to the closest integer. 
  • Minutes are basically the remainder of TimeCounter / 3600 divided by 60 (also, round down)
  • Seconds are simply the remainder of TimeCounter / 60 (also, round down)
After calculations we still have to do some formatting for the output. This is done with string.format() function, as seen in the C# example script. Formatted string is written out to console using Debug.Log() function. 

After writing (or copying) the script you can go back to Unity. Select "Console" tab, hit "Clear" and "Collapse" buttons, and then run your scene. Now you should see Debug.Log messages showing the content of TimeCounter, formatted to HH:MM:SS.

If you want to speed up testing, you can go back to editor and tweak line containing "Time.deltaTime" a bit:

TimeCounter += Time.deltaTime * 30;

This makes counter to run 30 times faster and you should still to be able to get 1 second increments to your Debug.Log messages.

Although this very simple and short example, I am sure someone might find this useful. 



Popular posts from this blog

Construct 2: if-then-elseif-else statement

Issue with Unity3D: "Found plugins with same names, and ."