Waiting for a Coroutine to finish doesn't work

Hi,

I have been reading a lot of “Answers” to this problem and none of them work - at all.

I have an Event like Start or Input event and I want that event to trigger a coroutine which will fade in an image. After the image is faded in I want it to fade out.

Sounds really simple, tried everything, can’t get it to work:

void Start ()
	{
		StartCoroutine ("EasterEgg");
	}

//...

private IEnumerator EasterEgg()
	{
		yield return StartCoroutine("FadeIn");
		//yield return new WaitForSeconds (2f);  //tried this as an alternative solution, also didn't work (never executes second Coroutine
		StartCoroutine ("FadeOut");
	}
	
	public IEnumerator FadeIn ()
	{
		SpriteRenderer logo = transform.FindChild("Logo").GetComponent<SpriteRenderer>();
		while (logo.color.a < 255) 
		{
			logo.color = new Color (logo.color.r, logo.color.g, logo.color.b, logo.color.a + 0.01f);
			yield return null;
		}
		Debug.Log ("!!!I was here!"); //This NEVER gets printed
	}

	public IEnumerator FadeOut ()
	{
		SpriteRenderer logo = transform.FindChild("Logo").GetComponent<SpriteRenderer>();
		while (logo.color.a > 0) 
		{
			logo.color = new Color (logo.color.r, logo.color.g, logo.color.b, logo.color.a - 0.01f);
			yield return null;
		}
	}

What it does:

  • Fades the logo in,

… that was it… It doesn’t print anything, doesn’t fade it out nothing.

I would be REALLY glad if somebody could explain this to me, thanks.

The color alpha value is a float between 0 and 1. not 0 - 256. Change this line:

 while (logo.color.a < 255) 
 //to
 while (logo.color.a < 1f)

Internally, the r, g, b and a values of a color is a value between 0 and 1, not 0 and 255. So your image will be faded in completely after the a reaches 1. Then, the code will keep increasing that value until you hit 255

I tried to run your code, and it does keep increasing the alpha value. Adding .01f every frame means that it takes 255/0.01 = 25500 frames for the alpha to reach 225. With 60 fps, that’s 425 seconds, or a little over 7 minutes before your coroutine ends.

To solve this, have the coroutine run until your alpha hits 1. I’d also make the algorithm framerate-independent by using deltaTime - if you want your logo to fade in over 2 seconds, that would be:

while (logo.color.a < 1f) {
    logo.color = new Color(logo.color.r, logo.color.g, logo.color.b, logo.color.a + (.5f * Time.deltaTime));
    yield return null;
}

Hope that helps!