Displaying a digital clock

Whether it is the real-world time, or an in-game clock, many games are enhanced by some form of clock or timer display. The most straightforward type of clock to display is a string composed of the integers for hours, minutes, and seconds:

Displaying a digital clock

How to do it...

To display a digital clock, please follow these steps:

  1. Attach the following C# script class to the Main Camera:
    // file: ClockDigital.cs
    using UnityEngine;
    using System.Collections;
    
    using System;
    
    public class ClockDigital : MonoBehaviour 
    {
      void OnGUI () 
      {
        DateTime time = DateTime.Now;
        string hour = LeadingZero( time.Hour );
        string minute = LeadingZero( time.Minute );
        string second = LeadingZero( time.Second );
    
        GUILayout.Label( hour + ":" + minute + ":" +  second);
      }
    
    
      /**
       * given an integer, return a 2-character string
       * adding a leading zero if required
       */
      private string LeadingZero(int n)
      {
        return n.ToString().PadLeft(2, '0'),
      }
    }

How it works...

Importing the System namespace allows the current time to be retrieved from the system using the DateTime class. The first line of the OnGUI() method retrieves the current time and stores it in a time DateTime object.

Integers for the hour, minute, and second are extracted from the DateTime object, and converted into two-character strings with the LeadingZero() method. This method pads out single digit values with a leading zero if required.

Finally, a string concatenating the hour, minute, and second strings with a colon separator is displayed via a GUI label.

There's more...

Some details you don't want to miss.

Converting to a 12-hour clock

If you prefer to display the hours in the 12-hour format, this can be calculated by finding the modulo 12 value of the 24-hour clock integer stored in the DateTime objects:

  int hour12 = time.Hour % 12;

See also

  • The Displaying an analogue clock recipe.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.189.251