Realtime clock

How do I make a real time clock in my game so that the player can see it?
Would I do it like so:

var dt = Date();
private var textMesh : TextMesh;
var day = dt.Now.Day.ToString();
var month = dt.Now.Month.ToString();
var year = dt.Now.Year.ToString();
var hours = dt.Now.Hour.ToString();
var minutes = dt.Now.Minute.ToString();
if (parseInt(minutes) < 10) minutes = "0" + minutes;
var seconds = dt.Now.Second.ToString();
if(parseInt(seconds) < 10) seconds = "0" + seconds;

function Start () {
    textMesh = GameObject.Find ("Timer").GetComponent(GUIText);
    textMesh.text = hours.ToString(); 
	textMesh.text = minutes.ToString();
	textMesh.text = seconds.ToString();
}

And how do I have it the the time (and date) gets updated?

It’s way simpler ;). btw you assign hours, minutes and seconds to the same textmesh so you override the others and only the seconds will show up.

Like Ashkan said a coroutine would be the best since the time needs only an updated per sec. It’s better to update at least 2 times a sec. to avoid synchronisation interferences.

function Updatetime()
{
    while(true)
    {
        var today = System.DateTime.Now;
        textMesh.text = today.ToString("yyyy-MM-dd_HH:mm:ss");
        yield WaitForSeconds(0.2f); 
    }
}

function Start()
{
    Updatetime();
}

I don’t know what format you want but you can change the format string as you like :wink: Take a look at the this page.

just update the text of textMeshes or any other text element that you want to show your date/time in in Update
use something like this in your Update

function Update ()
{
textMesh.text = td.Now.Minutes.ToString();
}

i did not checked for minutes less than 0 but you can and should do it to display 09 instead of 9 as you did yourself in declarations.

now you are using only a textmesh and rewriting it’s value 3 times show it will show the seconds. use dt.Time.ToString() to get the complete time in Update or use += for minutes and seconds to concatinate strings instead of replacing them. keep in mind that these string processings are time and memory consumming so doing it in a coroutine instead of Update (for example 5 times a second) can help much. after all the time will not change 70 times a second. so the same hh:mm:ss will be computed and displayed.

function UpdateTime()
{
while(true)
{
//calculate times and update strings
yield WaitForSeconds(0.2f); //5 times a second
}
}

and start this UpdateTime in Start/Awake.

I ended up doing this for the new UI system (have to add using UnityEngine.UI namespace)

public Text textDate;
//had to attach a UIText component to this

//then in some script

IEnumerator UpdateTime()  {
	while(true)
	{
		var today = System.DateTime.Now;
		textDate.text = today.ToString("yyyy:MM:dd @ HH:mm:ss");
		yield return new WaitForSeconds(0.2f);
	}
}

And then call StartCoroutine(UpdateTime()) from the Start()

Not sure if I need the while(true) clause, but it works.