Fading sprite's alpha via coroutine

Trying to fade a sprite via a coroutine. What am I doing wrong? Should I not be using coroutines? Right now it immediately turns to black instead of over time. (fader is the Sprite Renderer I’m trying to fade.)

void OnTriggerEnter2D(Collider2D other) {
	if (other.CompareTag("Door")) {
		StartCoroutine("FadeIn", fader);
	}
}
IEnumerator FadeIn(SpriteRenderer rend) {
		for (int i = 0; i <= 255; i++) {
			rend.color = new Color(rend.color.r, rend.color.g, rend.color.b, i);
			yield return new WaitForSeconds(0.01f);
		}
	}

1 Answer

1

Colors in unity are floats and go from 0.0 to 1.0. You are setting alpha from 0 to 255. You can divide i by 255.0 to make your existing code work. Here is more info on fading:

http://wiki.unity3d.com/index.php/Fade

Plus the code to fade colors has been posted to UA many times.

Note: How the alpha channel is handled depends on the shader. To make something transparent using the main color property, you will have to use a shader that has a main color and supports transparency.