- Home /
Format String Minutes:Seconds
Hi I'm making a timer that counts down a variable. I'm trying to format the string in my GUI. The variable is time in seconds.
Is it possible to keep this one variable or do I need to split the variables into minutes and seconds? And what's the line for formatting time?
keeping just one variable you could probably have a line like
print((TimeVariable % 60) + ":" + (TimeVariable - (TimeVariable % 60) * 60));
though it could be more efficient and easier to do it a different way or with two variables, I am unsure.
Answer by whydoidoit · May 29, 2012 at 08:30 PM
Try this for size:
var someString = String.Format("{0:0}:{1:00}", Mathf.Floor(yourTime/60), yourTime % 60);
Perfect, but apparently the $$anonymous$$ute number stays even tough the $$anonymous$$ute is over. Like if I have 120 seconds the timer states 2:00 then after two seconds 2:58. Is there any way to avoid this?
Sorry yes of course I guess it is rounding it up!
try:
var someString = String.Format("{0:0}:{1:00}", $$anonymous$$athf.Floor(yourTime/60), yourTime % 60);
Answer by flamy · May 29, 2012 at 08:43 PM
This is just a elaborate version of @mike's solution
#pragma strict
var time:int=0;
function Start () {
time=100;
InvokeRepeating("countDown",1f,1f);
}
function Update () {
}
function countDown()
{
time-=1;
}
function OnGUI(){
var minute:int = (int) Mathf.Abs(time/60);
var seconds:int =time%60;
var labelString: String=minute.ToString("00")+":"+seconds.ToString("00");
GUILayout.Label(labelString);
}
Answer by Threezool · Oct 26, 2015 at 12:30 PM
Made my own version to display a "time elapsed" counter in Unity 5 and display it in a canvas:
DateTime startTime;
TimeSpan elapsedTime;
void Start () {
startTime = DateTime.Now;
}
void LateUpdate () {
elapsedTime = DateTime.Now - startTime;
string displayTime = String.Format("{0:00}:{1:00}:{2:000}",
elapsedTime.Minutes,
elapsedTime.Seconds,
elapsedTime.Milliseconds);
GetComponent<Text>().text = displayTime;
}
Dont forget to add "using System;" to be able to use DateTime.
Your answer
Follow this Question
Related Questions
Coroutine Countdown Timer being extremely slow 1 Answer
Problem with countdown timer. 3 Answers
how to make a varied countdown timer 1 Answer
Timer doesn't work properly 2 Answers