At the end of game play, this example explains how to flash the “GAME OVER” message on and off.
This example starts out with the message appearing in the game view when the player’s last ship is damaged.
Message starting point, no flashing
Start with long variable names to help recognize flash timing, toggle on/off, message object, and the name for the IEnumerator method. Long variable names are helpful when passing values around in and out of methods.
(a) first use hard number values, then
(b) add variables, then [SerializeField] variables.
public class UIManager : MonoBehaviour
{
...
[SerializeField]
private Text _gameOverText;
public void ShowGameOver()
{
StartCoroutine(Flicker( _gameOverText ));
}
private IEnumerator Flicker(Text messageObject, float timing)
{
int count = 5;
while ( count-- > 0 )
{
_toggleOnOff = !_toggleOnOff;
messageObject.gameObject.SetActive( _toggleOnOff );
yield return new WaitForSeconds( 0.5f );
}
}
}
One by one, replace constants with variables:
public class UIManager : MonoBehaviour
{
...
[SerializeField]
private Text _gameOverText;
[SerializeField]
private float _textFlashInterval = 0.5f;
private bool _toggleOnOff;
public void ShowGameOver()
{
StartCoroutine(Flicker(_gameOverText, _textFlashInterval));
}
private IEnumerator Flicker(Text messageObject, float timing)
{
while (true)
{
_toggleOnOff = !_toggleOnOff;
messageObject.gameObject.SetActive(_toggleOnOff);
yield return new WaitForSeconds(timing);
}
}
}