- Home /
How can I use TimeSpan inside OnGUI to show a simple countdown timer with hours minutes seconds and milliseconds ?
void OnGUI()
{
TimeSpan timer = new TimeSpan(1, 1, 50);
TimeSpan deltaTimeSpan = TimeSpan.FromSeconds(Time.deltaTime);
timer = timer.Subtract(deltaTimeSpan);
string t = "Time left: " + timer.ToString("hh\\:mm\\:ss");
EditorGUILayout.LabelField("Next: ", t);
}
The problem is that ToString have not arguments. I'm getting error on ToString: No overload for method 'ToString' takes 1 arguments
What I want to do is to display a simple ctountdown timer with hours minutes seconds milliseconds on a LabelField. But can't do it.
Answer by KittenSnipes · Sep 26, 2018 at 05:45 PM
@Chocolade If I remember correctly it is because you do not have the input for the ToString method in a correct format. I think it should be like this:
void OnGUI()
{
TimeSpan timer = new TimeSpan(1, 1, 50);
TimeSpan deltaTimeSpan = TimeSpan.FromSeconds(Time.deltaTime);
timer = timer.Subtract(deltaTimeSpan);
//I added @ in front of the quotation marks in ToString
string t = "Time left: " + timer.ToString(@"hh\\:mm\\:ss");
EditorGUILayout.LabelField("Next: ", t);
}
Still not working I have tried it before.
I used for now a Timer and I can have hours $$anonymous$$utes and seconds.
t = new System.Timers.Timer();
t.Interval = 1000;//1s
t.Elapsed += T_Elapsed;
t.Start();
Then:
private void T_Elapsed(object sender, ElapsedEventArgs e)
{
if (s == 0)
{
s = 60;
m -= 1;
}
if (m == 0)
{
m = 60;
h -= 1;
}
s -= 1;
}
And in the end:
string t = string.Format("{0}:{1}:{2}", timer.Hours.ToString().PadLeft(2, '0'), timer.$$anonymous$$inutes.ToString().PadLeft(2, '0'), timer.Seconds.ToString().PadLeft(2, '0'));
EditorGUILayout.LabelField("Next: ", t);
All this is working fine with hours $$anonymous$$utes and seconds but now I wanted to add also milliseconds and still can't make it work with the TimeSpan.
I hope this works for you.
void OnGUI()
{
TimeSpan timer = new TimeSpan(1, 1, 50);
TimeSpan deltaTimeSpan = TimeSpan.FromSeconds(Time.deltaTime);
timer = timer.Subtract(deltaTimeSpan);
//Well I got home and I figured out a ok looking way
string t = "Time left: " + ToCustomString(timer);
EditorGUILayout.LabelField("Next: ", t);
}
Silly me I forgot to post the function with it. In a few hours you will see this fixed. Sorry about that I was quite tired as it was late
Your answer
Follow this Question
Related Questions
How can i pick two randomly items from gameobject array ? 1 Answer
Script for a hue rainbow scroll on the material 1 Answer
How can i using a break point if a gameobject have a collider after added to it ? 1 Answer
How can i get all childs from List ? 3 Answers
How can i set the same script on two GameObjects so the script will work on both objects same time ? 1 Answer