Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fade out Unity UI text

When I run the following code on my UI text

Color color = text.color;
color.a -= 1.0f;
text.color = color;

The alpha value of the text is immediately set to 0. How can I simply fade out the text.

like image 203
Isaac Adni Avatar asked Jan 11 '15 08:01

Isaac Adni


4 Answers

If you are using Unity 4.6 and newer you can take advantage of CrossFadeAlpha and CrossFadeColor.

Example:

// fade to transparent over 500ms.
text.CrossFadeAlpha(0.0f, 0.05f, false);

// and back over 500ms.
text.CrossFadeAlpha(1.0f, 0.05f, false);

These two functions are a bit nicer to use since you don't have to worry about keeping track of anything. Just call it and go about your day.

like image 200
Jonathan Avatar answered Nov 17 '22 22:11

Jonathan


You can use Coroutines:

Example:

public Text text;
public void FadeOut()
{
    StartCoroutine(FadeOutCR);
}

private IEnumerator FadeOutCR()
{
    float duration = 0.5f; //0.5 secs
    float currentTime = 0f;
    while(currentTime < duration)
    {
        float alpha = Mathf.Lerp(1f, 0f, currentTime/duration);
        text.color = new Color(text.color.r, text.color.g, text.color.b, alpha);
        currentTime += Time.deltaTime;
        yield return null;
    }
    yield break;
}
like image 4
mayo Avatar answered Nov 17 '22 23:11

mayo


Color values in Unity work in a 0f..1f range, so:

  • 0.0f is 0% (or 0/255 as shown in the editor)
  • 0.5f is 50% (or 127.5/255)
  • 1.0f is 100% (or 255/255)

Subtracting by 1.0f is bringing the value to 0%. Try a different decrement like 0.1f:

color.a -= 0.1f;
like image 3
Chris McFarland Avatar answered Nov 17 '22 21:11

Chris McFarland


Add this to the update method or a coroutine -

if(text.color != Color.clear) Color.Lerp (text.color, Color.clear, fadeSpeed * Time.deltaTime);

like image 1
shreks7 Avatar answered Nov 17 '22 21:11

shreks7