- Home /
How do I display text with Countdown Timer Minutes and Seconds
I trying to display the the text time with the countdown timer on scene . I gotten an error CS0119 I want the timer text to look like this when the scene is on play Time : 2:38 , Time : 2:37 , like this. Here is some of my code.
using UnityEngine; using System.Collections; using UnityEngine.UI; public class clock : MonoBehaviour {
Text text;
public int Minutes;
public int Seconds;
private float realMinutes ;
private float realSeconds ;
public void Start()
{
text = GetComponent <Text> ();
realMinutes = Minutes ;
realSeconds = Seconds ;
}
void Update ()
{
text.text = "Time:" + Time;
realMinutes -= Time.deltaTime;
realSeconds -= Time.deltaTime;
Minutes = (int) realMinutes ;
Seconds = (int) realSeconds ;
}
}
Answer by rober-psious · May 02, 2016 at 02:57 PM
You can try with the next class;
using UnityEngine;
using UnityEngine.UI;
public class MyClock : MonoBehaviour
{
public int Minutes = 0;
public int Seconds = 0;
private Text m_text;
private float m_leftTime;
private void Awake()
{
m_text = GetComponent<Text>();
m_leftTime = GetInitialTime();
}
private void Update()
{
if (m_leftTime > 0f)
{
// Update countdown clock
m_leftTime -= Time.deltaTime;
Minutes = GetLeftMinutes();
Seconds = GetLeftSeconds();
// Show current clock
if (m_leftTime > 0f)
{
m_text.text = "Time : " + Minutes + ":" + Seconds.ToString("00");
}
else
{
// The countdown clock has finished
m_text.text = "Time : 0:00";
}
}
}
private float GetInitialTime()
{
return Minutes * 60f + Seconds;
}
private int GetLeftMinutes()
{
return Mathf.FloorToInt(m_leftTime / 60f);
}
private int GetLeftSeconds()
{
return Mathf.FloorToInt(m_leftTime % 60f);
}
}
I know this is old, but it still seems to work- for the most part. I can only make this work by adding $$anonymous$$utes into the slot in the Editor. What am I missing?
That's how it's intended to work, from the way it's made. The $$anonymous$$inutes field is initialized at 0 and it's value is untouched in Update()
and any of the methods that follows. If the value stays at 0, the if statement functionality in Update()
never gets called since there's no else paired with the parent if statement.
Your answer
![](https://koobas.hobune.stream/wayback/20220612075928im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Game Over Text When Timer Ends 2 Answers
Turn seconds into minutes and seconds MM:SS 1 Answer
Drawing GUI Text using Javascript 2 Answers
making a timer (00:00) minutes and seconds 10 Answers
How to stop a Countdown Timer? 1 Answer