- Home /
Rounding numbers of a timer
Hello,
I have a simple race game that makes a car travel on 1 axis, seen from the side.
now, whenever i go across the finish, it tells the time it took.
Everything is actually working as it should, but during racing, and while showing the ending time, i want the time to be displayed like 01:23:54 for minutes, seconds and fractions.
This is my code, could anyone help me with this?
var time : float;
var finished : boolean = false;
var timer : GUIText;
function Update(){
if(finished == false){
time += Time.deltaTime;
}
}
function OnTriggerEnter(hit : Collider){
if(hit.tag == "FinishLine"){
finished = true;
}
}
function OnGUI(){
if(finished){
timer.text = "Your time was: " + Mathf.Round(time);
}
else{
timer.text = Mathf.Round(time) +"";
}
}
Answer by mpavlinsky · Jan 27, 2012 at 10:33 PM
You could just use the .NET TimeSpan structure to get the seconds/minutes/hours like so:
TimeSpan ts = TimeSpan.FromSeconds(gameTime);
int hours = ts.Hours;
int minutes = ts.Minutes;
int seconds = ts.Seconds;
// etc
And then format the data accordingly using some String.Format() magic.
Thanks for the answer, and that solved the first part, but i'm not too familiar with the string.format(). I guess i need to know how to use string.format to show the time like 01:12:53.
string.Format("{0:00}:{1:00}:{2:00}", hours, $$anonymous$$utes, seconds);
Google is your best friend.
I've had to code that stuff from scratch for so many years on $$anonymous$$$$anonymous$$O scripting systems. I'd totally forgotten about those functions. :)
Thank you guys. $$anonymous$$uch appreciated, it worked like a charm :)
You're welcome. $$anonymous$$ark as answered, please. =)
Your answer
Follow this Question
Related Questions
Working with Time in Unity 0 Answers
Timer script not perfectly working 1 Answer
Ready Set Go timer 1 Answer
Simple Timer 2 Answers
Visual timer? Like CUT THE ROPE 2 Answers