- Home /
Best way to implement a one-shot timer
I have a situation where I have a method that will update a text field and show it, and that text stays on screen for x amount of time - say 5 seconds - then it automatically goes away again.
I know I can do that easily with a coroutine that starts up and fires after 5 seconds. The problem with that is that the text might be updated after, say, 2 seconds. The original coroutine would still fire and hide the text field too early - after 3 more seconds. It seems clunky to manually stop any running coroutines to fix that situation.
I used to use a language where you'd do it with a single oneshot timer, like this (pseudocode):
OneShotTimer myTimer {
.interval = 5000;
void OnTimerFires() {
HideText();
// OneShotTimer automatically stops; otherwise call .stop()
}
}
void ShowText(string text) {
myText.text = text;
myText.show()
myTimer.start()
}
If the timer was .start()-ed when it was already running, it'd reset, so the text would show for the correct time.
So, this is probably a dumb question, but I'm sure others must have had this situation before. What's the best way to do this in Unity/C#? A good way of doing it with coroutines? I know there's also a C# timer class - would that be better to use? Of course I could also check the time elapsed since ShowText was last called in the Update() method but I know that's much worse for performance. Thanks for any suggestions.
Answer by Avaista · Jul 31, 2012 at 02:01 AM
This would work in terms of simplicity, though it requires the retention of a timer and boolean value. Honestly it's not utterly terrible either way, unless you have this stuff everywhere.
public float killTime;
public bool showingText;
public float textTime;
IEnumerator ShowText()
{
killTime = Time.time + textTime;
if(!showingText)
{
showingText = true;
ShowText();
while(Time.time < killTime)
yield return null;// or yield return new WaitForSeconds(killTime-Time.time);
KillText();
showingText = false;
}
yield break;
}
Your answer
Follow this Question
Related Questions
Coroutine Countdown Timer being extremely slow 1 Answer
Can't get 2d bomb to explode on timer 2 Answers
Accuracy of timer issue please help 2 Answers