Search code examples
unity-game-enginefade

Fading TextMeshPro Alpha is instantly fading


I tried using LeanTween and now wrote my own coroutine, neither of them work. The goal is, to have the text of a TextMeshPro element fade in / out over a duration, which should be simple enough but apparently isn't. Here is the coroutine:

private IEnumerator FadeText(float target, float duration) {
        Color color = text.color;
        float timer = 0f;
        float alpha = color.a;
        while(timer < duration) {
            timer += Time.deltaTime;
            print($"{timer / duration}% is: {Mathf.Lerp(alpha, target, timer / duration)}");
            color.a = Mathf.Lerp(alpha, target, timer / duration);
            text.color = color;

            yield return new WaitForEndOfFrame();
        }
    }

The Debug.Log shows the correct values (going from 0 to 255 and vice versa over the desired duration) but the text simply pops in. Here is how the code above looks like (again: using LeanTween had the same result): Example

The text "upgrades" is supposed to fade in over 5 seconds, and fade out over 0.4 seconds.

Am i missing something?


Solution

  • look into the API -> Color

    Each color component is a floating point value with a range from 0 to 1.

    The raw color type would be Color32 where rather

    Each color component is a byte value with a range from 0 to 255.

    So either

    • use a Color32 (there are implicit conversions between Color and Color32 so you can basically use them exchangeable, see Color32.Color and Color32.Color32)

    • or simply change the input value to be a float between 0 and 1.