# Why can't I stop Coroutine?

private IEnumerator FlickerEffectInTime()
{
while(true)
{
startTime += Time.deltaTime;
if (startTime < 2)
{
GetComponent<SpriteRenderer>().enabled = !GetComponent<SpriteRenderer>().enabled;
Debug.Log(startTime);
yield return new WaitForSeconds(0.1f);
}
else
{
startTime = 0;
GetComponent<SpriteRenderer>().enabled = true;
Debug.Log("stoped flick");
StopCoroutine("FlickerEffectInTime");

}
}
}


The while loop is infinite I have use StopCourotine() How can I resolve it ?

• This is just by the way, but things like visual flickering effects are often better done with the Animation System than via code. It's not just for making humanoid characters walk. It can be used to animate (almost) any property of any component. Jan 9 at 11:57

The routine won't stop on its own because, as you said, the while loop is infinite. Instead, replace the true in while(true) with a bool variable that you can set either inside or outside of the coroutine.

bool allowFlicker =true
while(allowFlicker)
{
// do stuff here

//time to stop? Then set allowFlicker false
allowFlicker = false
}


This looks like it could also be simply placed in the Update or FixedUpdate functions.

• Thanks for cleaning up my post, Theraot. Jan 9 at 13:42

The recommended way to make a coroutine end itself is to exit all the loops and have it run to the end. For example, if you want the coroutine to stop when startTime gets larger than 2f, you can do this:

private IEnumerator FlickerEffectInTime()
{
while(startTime < 2.0f)
{
startTime += Time.deltaTime;
GetComponent<SpriteRenderer>().enabled = !GetComponent<SpriteRenderer>().enabled;
yield return new WaitForSeconds(0.1f);
}

startTime = 0;
GetComponent<SpriteRenderer>().enabled = true;
}


However, sometimes that's not feasible. In that case there is a better alternative to self-terminating the coroutine with StopCoroutine. Just use the statement yield break;. It signals to the code which processes an IEnumerator that the enumeration has ended and the enumerator can be disposed. Which in the context of Unity Coroutine means that the coroutine should be stopped.