This short written tutorial is aimed to show you in a few easy steps how to code a timer in Unity 3 D. You can easily modify the script by doing minor changes. This tutorial will make use of the new Unity UI System that was introduced in Unity 4.6f. Its also tested with Unity 5 and works just fine.
1. Step: Let’s get started by opening up a new or a existing unity project. Go ahead and add in a new GUI-Text by clicking GameObject, UI and finally choose Text (third option).
2. Step: Adjust the Render Mode of the automatically generated object called “Canvas”. Set it from Screen Space – Overlay to Screen Space – Camera. That way the timer will be placed perfectly fine according to our camera. You also have to set the Render Camera: Set it to your Main Camera.
3. Step:Click on Add Component at the bottom of the inspector panel (make sure you have Text GameObject selected) and select new Script. Then you have to give you script a proper name and set the language to Java Script.
4. Step: After Opening the newly generated Script (by default it will be stored in your assets folder) you should see this:
Replace everything thats currently in the script with the following code:
#pragma strict private var startTime : float; private var textTime : String; private var guiTime: float; //The gui-Time is the difference between the actual time and the start time. private var minutes : int; private var seconds : int; private var fraction : int; //Create a reference for the textfield private var textField : UI.Text; //First define two variables. One private and one public variable. Set the first variable to be a float. //Use for textTime a string. function Start() { startTime = Time.time; textField = GetComponent(UI.Text); } function Update () { guiTime = Time.time - startTime; //The gui-Time is the difference between the actual time and the start time. minutes = guiTime / 60; //Divide the guiTime by sixty to get the minutes. seconds = guiTime % 60;//Use the euclidean division for the seconds. fraction = (guiTime * 100) % 100; textTime = String.Format ("{0:00}:{1:00}:{2:00}", minutes, seconds, fraction); //text.Time is the time that will be displayed. textField.text = textTime; }
5.Step: Optional: Adjust the position text object and Set it to the x=0, y=0, z=0.
6. Step: Optional: If you want you could also change the font and the font size and color by adjusting the Text component of the text object.
7. Step: Give it a try!
Thats how my final result looks like:
Link to the Live Demo (HTML 5) click here.
I hope you did like this tutorial.
Links:
http://en.wikipedia.org/wiki/Euclidean_division
http://docs.unity3d.com/Documentation/ScriptReference/
Cheers,
Alex
