- Home /
Minutes and Seconds in a text
Hey guys, i am making a CountDown Timer, and it work, but not as i wanted. I made it very simple in C#. It's basically a float that is changed over time, and it is shown in a text. If i set the float to 900 (15 minutes), then the text is going to be shown like 900 normally. What i want to do is, if i set the float to 900, then in the text, it will show something like 15:00. How would i do that? I have no idea of how to start.
This is my script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Timer : MonoBehaviour
{
public float timeLeft = 900.0f;
public Text text;
bool clock;
private float mins;
private float secs;
void Update()
{
if (timeLeft > 0 && clock == false)
{
clock = true;
StartCoroutine(Wait());
}
}
IEnumerator Wait()
{
timeLeft -= 1;
UpdateTimer();
yield return new WaitForSeconds(1);
clock = false;
}
void UpdateTimer()
{
text.GetComponent<UnityEngine.UI.Text>().text = timeLeft.ToString();
}
}
Could someone help me to change the text format so it show things like real minutes and seconds? Thanks in advance! Btw someone said to me that i would need to use math to change the mins and secs variables, but i don't know how to do it and in what it would help actually =\
There is an answer on StackOverflow using the .NET TimeSpan class: What is the best way to convert seconds into (Hour:$$anonymous$$inutes:Seconds:$$anonymous$$illiseconds) time
You could also do some maths by dividing the seconds by 60 to get the total time in $$anonymous$$utes, get the decimals (the figures after the decimal point) from it to get the seconds by multiplying again by 60, get the time in hours by dividing the $$anonymous$$utes (without the figures after the decimal point) by 60, get the decimals from it to get the $$anonymous$$utes by multiplying by 60, etc...
This question is not related to Unity, but to general C# scripting, though. ;)
Answer by Bunny83 · Nov 28, 2016 at 08:48 PM
Just do this:
int min = Mathf.FloorToInt(timeLeft / 60);
int sec = Mathf.FloorToInt(timeLeft % 60);
text.GetComponent<UnityEngine.UI.Text>().text = min.ToString("00") + ":" + sec.ToString("00");
FloorToInt will round the given value down to the nearest integer. So 14.3215
becomes 14
.
Dividing your whole time in seconds by 60 gives you minutes but with fractional part so rounding down to int gives you whole minutes
Taking the modulo 60 (division remainder) of the whole time in seconds will give you only the actual seconds Example 885 --> 885 / 60 --> 14 remainder 45. So the time is 14 minutes and 45 seconds.
Your answer
Follow this Question
Related Questions
Turn seconds into minutes and seconds MM:SS 1 Answer
Clock Script From Java to C# Help 1 Answer
making a timer (00:00) minutes and seconds 10 Answers
How Would I Change This To Read Within A Time Range? 1 Answer
How to stop a Countdown Timer? 1 Answer