- Home /
Question by
timmyiscool8 · Dec 19, 2018 at 04:10 AM ·
c#uitext
C# UI Text not updating
I know, tons of people have asked this question. I have gone to all of those posts, and none of the solutions have solved my problem. I have a countdown timer that is formatted to display mm:ss which it does. I have a UI text object assigned to this, so it sets the text's text, (text.text) to that formatted string. The unity inspector shows the countdown working, but the UI text object doesn't update. Script:
using System.Collections;
using UnityEngine.UI;
using UnityEngine;
public class CountdownTimer : MonoBehaviour
{
public float timeLeft = 300.0f;
public bool stop = false;
private float minutes;
private float seconds;
public Text text;
public void startTimer(float from)
{
stop = false;
timeLeft = from;
Update();
StartCoroutine(updateCoroutine());
}
void Update()
{
if (stop) return;
timeLeft -= Time.deltaTime;
minutes = Mathf.Floor(timeLeft / 60);
seconds = timeLeft % 60;
if (seconds > 59) seconds = 59;
if (minutes < 0)
{
stop = true;
minutes = 0;
seconds = 0;
}
// fraction = (timeLeft * 100) % 100;
}
private IEnumerator updateCoroutine()
{
while (!stop)
{
text.text = string.Format("{0:0}:{1:00}", minutes, seconds);
yield return new WaitForSeconds(0.2f);
}
}
}
Comment
Answer by Coffee-with-Venky · Dec 19, 2018 at 09:04 AM
@timmyiscool8 where did you called this method ?
public void startTimer(float from)
{
stop = false;
timeLeft = from;
Update();
StartCoroutine(updateCoroutine());
}