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:
To display a digital clock, please follow these steps:
// 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'), } }
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.
Some details you don't want to miss.
3.144.30.236