- Home /
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);
}
}
Answer by robertbu · Dec 12, 2013 at 07:31 AM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613124002im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Coroutine cannot be automatically started from a static function 1 Answer
Fading out GUI Label using coroutine problem 2 Answers
Unity2D Sprite Fading Issues 1 Answer
Fading Issue 2 Answers
8 Directional sprite in 3d world, how to retrieve angle? 2 Answers