- Home /
yield return new WaitForSeconds not working
I am trying to make my text flicker through my script which I have done before but for some reason, the yield return new WaitForSeconds isn't registering...
Please help thanks!
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class UIManager : MonoBehaviour { [SerializeField] private Text blue; [SerializeField] public float _flicktime = 1f;
public bool BLUETEXT = false;
void Start()
{
BLUETEXT = false;
blue.gameObject.SetActive(false);
}
void Update()
{
StartCoroutine(BlueFlickerRoutine());
}
IEnumerator BlueFlickerRoutine()
{
while(BLUETEXT == true)
{
blue.gameObject.SetActive(true);
yield return new WaitForSeconds(_flicktime);
blue.gameObject.SetActive(false);
yield return new WaitForSeconds(_flicktime);
}
}
}
Answer by JavaMcGee · Jun 18, 2020 at 07:46 PM
Might be because you're calling the coroutine on every Update when bluetext is true, so you're starting the same coroutine again and again, and the first thing the routine does is SetActive(true). I think you'd just want to start the routine once.
A small change to try, remove the startcoroutine from Update, make blueText as a private variable, and use a function to start the routine:
public bool StartFlicker() {
blueText = true;
StartCoroutine(BlueFlickerRoutine());
}
public bool StopFlicker() {
blueText = false;
}
You could connect these function to a button or call from whatever you're using to trigger the flicker.