Tip of The Day: Going Retro with Texts in Unity
If you have ever played arcades in the 80s or 90s or even now a days, you surely have seen those flashy titles or texts that blink in and out.
Objective
Create blinking text in Unity two ways
Way One: The Animator
The simplest and easiest way is to animate the text.
- Create your Text UI and attach to it an Animator Component
2. Select the Text you want to animate, and in the animation tab (while the object is selected) click on “create”, this will allow you to create a new animation, save it.
3. Press the record button in the animation, deactivate the text component in the text UI object, choose an interval (say 0.25 sec), activate it, and the deactivate it after 0.5sec. The animation will loop blinking your text.
Way Two: The coder
This method allows you to achieve the blinking effect through code and here is how to do it in few simple steps
- In the script create a reference for the text UI object and serialize it in order to see it in the inspector
2. Create an IEnumerator routine and here we can do it in two different ways.
A) Set the text component to whatever string you want, yield for a delay, then set the text again to nothing “ “ and yield again. This method is a little more efficient.
IEnumerator GameOverFlickerRoutine()
{
while(true)
{
gameoverText.text = "GAME OVER";
yield return new WaitForSeconds(0.35f);
gameoverText.text = "";
yield return new WaitForSeconds(0.35f);
}
}
B) You set the text in the inspector, and in the IEnumerator you deactivate the text component, wait a little bit, activate the text component, and then wait for a little bit again.
IEnumerator GameOverFlickerRoutine()
{
while (true)
{
gameoverText.GetComponent<TextMeshProUGUI>().enabled = true;
yield return new WaitForSeconds(0.35f);
gameoverText.GetComponent<TextMeshProUGUI>().enabled = false;
yield return new WaitForSeconds(0.35f);
}
}
Remember that in both cases you do it in a while(true) loop, this will allow this animation to run continuously as long as the Text UI gameObject is active
Here is how it looks in both cases