In this artcile we see how to show the current system time in Unity in a text from the user interface.
This could be useful for example to have a VR smartwatch and display the system time in a world space Canvas attached to that smartwatch.
This solution is in the “GDT Solutions for Unity” GitHub repository
There is a video tutorial on this topic:
Procedure to create a Script that controls a digital clock
This article is about how we can read the system time in Unity and showing it on a text in the Canvas
First of all let’s create a new script and also create an empty GameObject to assign the script, as shown in the following images
Inside the script declare the TMPro namespace and define a TMP_Text variable, call it for example “text_currentTime“, as shown in the lines 3 and 8 of the following image.
In the hierarchy, inside your Canvas, create a new Text Mesh Pro object. If you don’t have a Canvas Unity will create one for you.
In case you need it, here is a video on how to work with Text Mesh PRO, you may want to check it, if it’s the first time using it.
Select the GameObject object that has the script, take the Text Mesh Pro object and drop it in the field in the inspector that corresponds to the TMP_Text variable we defined. By doing this, now we have the reference of the text object in our script and we can modify it by code.
Inside our script, let’s add the “System” namespace and define a “DateTime” type variable, call it for example “currentTime“.
Inside Update we are gonna assign to that variable, the following instruction (pay attention to uppercase characters):
currentTime = DateTime.Now;
We can use this currentTime variable to get information about the current time, for example which hour it is, the current minute and the current second. So let’s define a couple local int variables to temporarily assign those values.
int hour = currentTime.Hour;
int minute = currentTime.Minute;
int second = currentTime.Second;
Now that we have all the information we need, we can show the system time in our Unity game in the user interface using the TMP_Text variable we defined, and we can do so in the following way:
text_currentTime.text = hour.ToString(“00″)+”:”+minute.ToString(“00”)+”:”+second.ToString(“00”);
Hit play and you should be seeing that it is working.
Adapt this solution to create a VR smartwatch in Unity
This solutions works exactly the same if you want to display the current time on a VR smartwatch, the difference is that you probably will need to configure the Canvas as World Space, assign your VR camera in the canvas field in the inspector and attach the Canvas object as a child of the Hand anchor of your VR controller.
You have reach the end of the article, if it was useful consider subscribing to the channel!