Hey,
I’m trying to make a timer (in the format minutes/seconds/milliseconds) for my racing game but whenever the seconds reaches 30, the minutes go up. The script I’m using is below.
private var startTime;
var textTime : GUIText;
function Awake() {
startTime = Time.time;
}
function Update() {
var guiTime = Time.time - startTime;
var minutes : int = guiTime / 60;
var seconds : int = guiTime % 60;
var fraction : int = (guiTime * 100) % 100;
textTime.text = String.Format ("{0:00}:{1:00}:{2:00}", minutes, seconds, fraction);
}
I’ve tried changing the line
var minutes : int = guiTime / 60;
to
var minutes : int = guiTime / 120;
but then the minutes only go up when the seconds reach 60 twice (i.e. every 2 minutes).
Any help?
Sorry about the bump, but does anyone have anything that may help?
When the result of the division is converted to integer, it is rounded, so when the fractional part goes above .5, it is rounded up to the next integer. You need to use Mathf.FloorToInt to make sure you always get the lower integer:-
var minutes : int = Mathf.Floor(guiTime / 60);
Cheers,
Just tested it out and it works like a charm.
hi I have modified your code like this was true. Works.'ve Tested
var startTime = 0;
function Update () {
//The time taken so far
timeTaken = startTime + Time.time;
// Format the time nicely
guiText.text = FormatTime (timeTaken);
}
//Format time like this
// 17[minutes]:21[seconds]:05[fraction]
function FormatTime (time)
{
var intTime : int = time;
var minutes : int = intTime / 60;
var seconds : int = intTime % 60;
//var fraction : int = time * 10;
// fraction = fraction % 10;
//Build string with format
// 17[minutes]:21[seconds]:05[fraction]
// timeText = minutes.ToString () ;
//timeText = timeText + seconds.ToString ();
timeText = String.Format ("{0:00} {1:00}", minutes, seconds);
// timeText += fraction.ToString ();
return timeText;
}
I was reading this thread trying to get the same thing working. himan’s code works great, except I want to get the fraction time to have two units instead of just one. If anyone can provide a dummy’s guide to how String.Format works I’d really appreciate it. I have no clue why {0:00},{1:00} works the way it does and my timer just refuses to be formatted correctly. I’ve currently got it at {0:00}:{1:00}:{2:00} and my time comes out as 00:00:000 minutes:seconds:miliseconds. The first zero of miliseconds never changes.
What am I doing wrong?
C#
I made this and test was ok:
private string FormatTime (float time){
float totalTime = time;
int hours = (int) (totalTime / 3600);
int minutes = (int) (totalTime / 60) % 60;
int seconds = (int)totalTime % 60;
string answer = hours.ToString ("00") + ":" + minutes.ToString("00") + "." + seconds.ToString("00");
return answer;
}
1 Like