- Home /
How do I have a 2D sprite fade in and out? (C#)
Hello, I have an enemy that has a sprite attached to it. I would like to fade this enemy in for a period of time and fade out for a period of time. I am having trouble creating a good method to do this. I already have been able to alter the alpha of the sprite, I'm just having trouble with the fade in and out part.
Thank you!!!
Answer by deniskotpletnev · Jul 29, 2020 at 06:36 AM
I don't have your code, but here's a template by which you can do everything yourself:
     SpriteRenderer yourSpriteRenderer;
     private IEnumerator FadeIn()
     {
         float alphaVal = yourSpriteRenderer.color.a;
         Color tmp = yourSpriteRenderer.color;
 
         while (yourSpriteRenderer.color.a > 0)
         {
             alphaVal -= 0.01f;
             tmp.a = alphaVal;
             yourSpriteRenderer.color = tmp;
 
             yield return new WaitForSeconds(0.05f); // update interval
         }
     }
 
     private IEnumerator FadeOut()
     {
         float alphaVal = yourSpriteRenderer.color.a;
         Color tmp = yourSpriteRenderer.color;
 
         while (yourSpriteRenderer.color.a < 1)
         {
             alphaVal += 0.01f;
             tmp.a = alphaVal;
             yourSpriteRenderer.color = tmp;
 
             yield return new WaitForSeconds(0.05f); // update interval
         }
     }
You can run it like this:
         StartCoroutine(FadeIn());
Your answer
 
 
             Follow this Question
Related Questions
How can i get my gameobject as a sprite from its collider name? 1 Answer
Is there a way to change the sprite for all instances of the same object simultaneously? 1 Answer
How the change the sprite image of spritemask according to the sprite image in that object animator? 0 Answers
How do I make individual pixels of my objects sprite change color/disappear? 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                