- Home /
 
Having trouble. Trying to fade out a sprite after 5 seconds over the course of a second or two.
After five seconds the sprite just disappears instantly. I got it from the manual specifically because it said it wouldn't do that. http://docs.unity3d.com/Manual/Coroutines.html The only changes made to the script was that I added the 5 second wait "startFade" (it was still disappearing immediately before I added that) and I had to change "renderer" to "GetComponent()"
[CODE]
using UnityEngine; using System.Collections;
 public class FadeSprite : MonoBehaviour 
 {
     public float fadeWait = 5;
 
     void Start () 
     {
         StartCoroutine (startFade (fadeWait));
     }
 
     IEnumerator Fade() 
     {
         for (float f = 1f; f >= 0; f -= 0.1f) 
         {
             Color c = GetComponent<Renderer>().material.color;
             c.a = f;
             GetComponent<Renderer>().material.color = c;
             yield return null;
         }
     }
 
     IEnumerator startFade(float wait)
     {
         yield return new WaitForSeconds(wait);
         StartCoroutine ("Fade");
     }
 }
 
               [/CODE]
Sorry I'm not sure if the code tags worked. I read this http://forum.unity3d.com/threads/using-code-tags-properly.143875/ and tried doing what it said but I'm not sure.
Answer by barbe63 · Jul 20, 2015 at 02:54 AM
Your color is faing way to quickly. Beside you should use Time.deltaTime to ensure it wouldn't be frame rate dependant like this:
      IEnumerator Fade() 
          {
              for (float f = 1f; f >= 0; f -= Time.deltaTime) 
              {
                  Color c = GetComponent<Renderer>().material.color;
                  c.a = f;
                  GetComponent<Renderer>().material.color = c;
                  yield return null;
              }
          }
 
 
               This would last 1s. If you want it to last more just divide Time.deltaTime by some number.
Answer by 12Buffy34 · Jul 20, 2015 at 02:08 AM
It looks like the Fade() function is leaving the material.color at 0 when the FOR loop ends. If you want the sprite to re-appear then capture the color before the FOR loop and restore it at the end.
Your answer
 
             Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unity streching sprite gameobject to fit two positions. 1 Answer
Sprite Swapping help 1 Answer
Question on Sprite and Movement 0 Answers