How to create a countdown timer and show current time in Unity3D
In this post I’m going to show you how to create a countdown timer and show current time in Unity3D.
- Create a new 2D project:
- Optionally download some background image (I used this one) and drag it to the Assets folder:
- Drag the background image to the Hierarchy:
- Adjust the size of the Camera to 8:
- Hierarchy->Create->UI->Text:
- Click on Canvas in Hierarchy and set the Render mode:
- Click on Text and change the settings (Positions, Width, Height, Text, Font Site):
- Rename the Text to TimerText
- Duplicate the TimerText and rename to TimeText:
- Change y position of TimeText to -200:
- Hierarchy -> Create -> Create Empty:
- Rename it to GameController
- Inspector -> Add Component -> New Script (name it Timer and select JavaScript):
- Paste the following code:
#pragma strict var timer: float = 70; var isFinishedLevel : boolean = false; public var displayText : UnityEngine.UI.Text; public var timeText : UnityEngine.UI.Text; var minsDisplay : String; var secsDisplay : String; var mySeconds : int = 0; private var oldTimer : float; function Start(){ oldTimer = timer; } function Update() { if (!isFinishedLevel) { timer -= Time.deltaTime; } CurrentTime(); } function CurrentTime() { var dt : System.DateTime = System.DateTime.Now; var h : int = dt.Hour; var m : int = dt.Minute; var s : int = dt.Second; timeText.text = h + ":" + m + ":" + s; if(mySeconds != s) { mySeconds = s; Timing(); } } function Timing() { if (timer > 0) { //var minsDisplay : String = parseInt( timer / 60 ).ToString(); minsDisplay = parseInt( timer / 60 ).ToString(); //var secsDisplay : String = parseInt( timer ).ToString(); secsDisplay = parseInt( timer ).ToString(); if ( (timer - ( parseInt(minsDisplay) * 60)) > 10 ) { secsDisplay = parseInt( timer - ( parseInt(minsDisplay) * 60) ).ToString(); } else { secsDisplay = "0" + parseInt( timer - ( parseInt(minsDisplay) * 60) ).ToString(); } //displayText.text = minsDisplay + " : " + secsDisplay; } else { timer += oldTimer; } displayText.text = minsDisplay + " : " + secsDisplay; }
- Drag TimerText and TimeText to the script from Hierarchy:
- [le problems] – Run the program, and you’ll run into few issues:
- If you open up any other window you will notice that the timer will stop, and continue counting once you return to the Unity window [edit: this seems to be expected behavior and in order to “fix” this, you have to set the “Edit -> Project Settings -> Player -> Run In Background” option (from here)]
- TimerText and TimeText are not “ticking off” at the same time [edit: this is now also fixed and the code is updated with the fix]
- If someone has info on how to solve this, please comment and I’ll update the post once the solution is found [edit: both issues have been resolved thanks to Unity Answers, I’m just leaving them here for some future reference].
Leave a Comment