- Home /
How to make this display milliseconds?
I am making a timer where they have a certain amount of time to beat a level, and I want it to display milliseconds as well. How do I do that?
public float timeLeft = 15f;
public GameObject player;
public GameObject environment;
[Header("UI Components")]
public Text timer;
public GameObject timerText;
public GameObject healthText;
public GameObject shieldText;
public GameObject livesText;
public GameObject skipsText;
public GameObject pointsText;
public GameObject respawnScreen;
private bool dead;
private void Update()
{
timeLeft -= Time.deltaTime;
UpdateLevelTimer(timeLeft);
if (timeLeft <= 0)
Die();
}
private void UpdateLevelTimer(float totalSeconds)
{
int minutes = Mathf.FloorToInt(totalSeconds / 60f);
int seconds = Mathf.RoundToInt(totalSeconds % 60);
float milliseconds = Mathf.FloorToInt(totalSeconds * 1000);
string formatedSeconds = seconds.ToString();
if (seconds == 60)
{
seconds = 0;
minutes += 1;
}
timer.text = minutes.ToString("00") + ":" + seconds.ToString("00") + "." + milliseconds.ToString("00");
timeLeft = Mathf.Clamp(timeLeft, 0, 12000000);
}
private void Die()
{
dead = true;
timerText.SetActive(false);
healthText.SetActive(false);
shieldText.SetActive(false);
livesText.SetActive(false);
skipsText.SetActive(false);
pointsText.SetActive(false);
respawnScreen.SetActive(true);
environment.SetActive(false);
Destroy(player);
print("Player has died.");
}
Answer by Schmit · Jun 27, 2019 at 07:27 PM
I'd recommend leveraging the TimeSpan class so you won't need to bother with the rounding and modding. You also gain flexible formatting through the ToString call.
You should be able to change the entirety of UpdateLevelTimer
to a single line:
timer.text = TimeSpan.FromSeconds(timeLeft).ToString("mm\\:ss\\.fff");
Answer by xxmariofer · Jun 27, 2019 at 06:04 PM
totalSeconds will be something like this:
totalSeconds = 14,956;
so if you want to print the ms you need to rest the seconds before multiplying * 1000
float milliseconds = ((float)totalSeconds - seconds) * 1000
Answer by MacFelon · Dec 09, 2021 at 08:31 AM
Use System.DateTime.Now.Millisecond, then on the next pull, do the same, or a combination of thus. Regular C# works in Unity also...
Your answer
Follow this Question
Related Questions
timer not ticking down 2 Answers
Timer reset 1 Answer
Timer counting UP instead of DOWN 1 Answer
Want to load scene after taking off in plane. 1 Answer
How to work a real life timer? 2 Answers