Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Coroutine Issue

Discussion in 'Scripting' started by FuzzyBalls, Jun 12, 2014.

  1. FuzzyBalls

    FuzzyBalls

    Joined:
    Jun 12, 2014
    Posts:
    47
    Hey,

    I'm having a small issue with my game, All I need to do is set the alpha of my sprite to 255, then lerp it to 0, I've programmed the logic but it doesn't seem to work :( The coroutine works on it's own, but when I set it to 255 first it doesn't work. So I tried to nest the coroutine within a coroutine but still doesn't work.

    If anyone has any idea and is willing to help out I'd appreciate it loads!

    Code (CSharp):
    1. IEnumerator ShieldFade() {
    2.         Color newColor = animationSettings.shieldRenderer.material.color;
    3.         newColor.a = 255f;
    4.         animationSettings.shieldRenderer.material.color = newColor;
    5.        
    6.         yield return StartCoroutine(FadeTo(0, 0.1f, animationSettings.shieldRenderer));
    7.     }
    then the fade coroutine :

    Code (CSharp):
    1. IEnumerator FadeTo(float aValue, float aTime, SpriteRenderer renderer) {
    2.         float alpha = renderer.material.color.a;
    3.         for (float t = 0.0f; t < 1.0f; t += Time.deltaTime / aTime) {
    4.             Color newColor = new Color(1, 1, 1, Mathf.Lerp(alpha, aValue, t));
    5.             renderer.material.color = newColor;
    6.             yield return null;
    7.         }
    8.     }
     
  2. one_one

    one_one

    Joined:
    May 20, 2013
    Posts:
    621
    You're making things a bit complicated. All you need is to use Color.Lerp, starting from Color.clear to Color.white. Also keep in mind that Lerp needs to be called every frame (so either in Update or a while(){ ... yield} coroutine).
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,398
    Color values range from 0 to 1; you wouldn't use 255 for anything.

    --Eric
     
  4. FuzzyBalls

    FuzzyBalls

    Joined:
    Jun 12, 2014
    Posts:
    47
    Ahh thanks Eric, Forgot about that completely! Just got confused since in the editor window it's displayed from 0 - 255. Thanks again tho.

    You're completely correct, Color.lerp would've worked fine. They both do the same thing.

    Is there any difference performance wise?
     
  5. one_one

    one_one

    Joined:
    May 20, 2013
    Posts:
    621
    Color32 ranges from 0-255 for each channel. I don't think there is a major performance difference but unless you're running this script on hundreds of objects simultaneously it really shouldn't matter at all. Did you get it to work calling it once every frame during the transition?