- Home /
The question is answered, right answer was accepted
How Can I make a Timer With The New UI System?
I have this Java script timer which works fine but I want to try and make one like this using the new U.I. system in C#? This is the one I currently have in Java.
#pragma strict
private var time : float;
var textTime : String;
var timerOn : boolean;
var buttonText : String;
var beep1 : AudioClip;
var beep2 : AudioClip;
var buttonTexture: Texture2D;
function Start() {
timerOn = false;
buttonText = "Start";
}
function Update(){
if(timerOn)
time += Time.deltaTime;
}
function OnGUI () {
var guiTime = time;
var minutes : int = guiTime / 60; //Divide the guiTime by sixty to get the minutes.
var seconds : int = guiTime % 60;//Use the euclidean division for the seconds.
var fraction : int = (guiTime * 100) % 100;
textTime = String.Format ("{0:00}:{1:00}:{2:00}", minutes, seconds, fraction);
//text.Time is the time that will be displayed.
GetComponent(GUIText).text = textTime;
}
public function TimerOnOff()
{
// do your timer on/off stuff
timerOn = !timerOn;
if(timerOn) buttonText = "Stop";
else buttonText = "Start";
audio.PlayOneShot(beep1);
}
public function TimerReset()
{
// do your timer reset stuff
time = 0;
audio.PlayOneShot(beep2);
}
Answer by Neamtzu · Feb 20, 2015 at 05:29 PM
Hi,
Create a new script from this code:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class timer : MonoBehaviour {
public Text timerLabel;
private float time;
void Update() {
time += Time.deltaTime;
var minutes = time / 60; //Divide the guiTime by sixty to get the minutes.
var seconds = time % 60;//Use the euclidean division for the seconds.
var fraction = (time * 100) % 100;
//update the label value
timerLabel.text = string.Format ("{0:00} : {1:00} : {2:000}", minutes, seconds, fraction);
}
}
Create a new GameObject, attach the script you created. Create a label. Select the first object you created and in inspector drag and drop the label in the timerLabel variable.
Thanks Neamtzu I'll give this a shot and see if it works out.
This needs to be explained better, I tried doing what you said but I think I am missing something. I think also that you are asking me to use part of the old OnGUI stuff which is what I am trying to steer clear of.?
No, if you're using Unity 4.6x you can create a text object (text, not label, sorry) GameObject->UI->Text. I'll edit the first answer.
So, your timerLabel variabile should have the type Text. Everything else should be ok now. Just create an text object and drag it in inpector in the timerLabel slot.
Follow this Question
Related Questions
Unity 5 - Time counter Up script (millisecond precision) UI 1 Answer
Clock Script From Java to C# Help 1 Answer
CanvasRenderer text is behind sprites 4 Answers
How Too Scrolling UI Text Message Centre 1 Answer
How to make a stopwatch that restarts every time the player dies and saves it as a highscore 3 Answers