How to fade TextMesh alpha with LeanTween?

Viewed 6184

I was looking for a way to fade the alpha value of TextMesh-Text in Unity, but I could not finde a solution online nor in the LeanTween Documentation.

  • LeanTween.alphaText() does only work with the normal UI-Text (not TextMesh)
  • LeanTween.alpha() doesn't do anything for me on Text.
4 Answers

After looking briefly through the API I guess a better way than introducing CanvasGroups just for fading one single text would rather be using LeanTwean.value for setting its color. CanvasGroup is a bit overkill here in my opinion.

(example adopted from API)

TextMeshProUGUI text;

void Start()
{
    text = GetComponent<TextMeshProUGUI>();
    var color = text.color;
    var fadeoutcolor = color;
    fadeoutcolor.a = 0;
    LeanTween.value(gameObject, updateValueExampleCallback, fadeoutcolor, color, 1f).setEase(LeanTweenType.easeOutElastic).setDelay(2f);
}


void updateValueExampleCallback(Color val)
{
    text.color = val;
}

You can also extend the LeanTween extension methods file (LeanTweenExt.cs) with the follow lines. This method will allow you to apply the LeanAlphaText on textMeshes like you're used to do on UI Texts.

public static LTDescr LeanAlphaText (this TextMesh textMesh, float to, float time) {
    var _color = textMesh.color;
    var _tween = LeanTween
        .value (textMesh.gameObject, _color.a, to, time)
        .setOnUpdate ((float _value) => {
            _color.a = _value;
            textMesh.color = _color;
        });
    return _tween;
}

I came up with my own solution.

Instead of changing the alpha of the TextMesh-Component directly, I add a CanvasGroup to the Gameobject that holds my TextMesh-Component. Then I manipulate the alpha value of the CanvasGroup instead.

To use my example code:

  1. On your Canvas go: [RightClick] > UI > Text - TextMeshPro
  2. Attach my example Script to this Gameobject. (This creates the required CanvasGroup automatically)
  3. Press Play (Ctrl + P)

After a delay of 2 Seconds (because of.setDelay(2f) the Text should fade in.

Examplecode:

using UnityEngine;
using TMPro;

[RequireComponent(typeof(CanvasGroup))]
public class LeanTweenTextFade : MonoBehaviour
{          
    private void Start()
    {
        CanvasGroup canvasgroup = this.gameObject.GetComponent<CanvasGroup>();
        TextMeshProUGUI infoTextTMPro = this.gameObject.GetComponent<TextMeshProUGUI>();

        canvasgroup.alpha = 0f;
        infoTextTMPro.text = "This Text should fade in.";

        float duration = 1f;
        LeanTween.alphaCanvas(canvasgroup, 1.0f, duration).setDelay(2f);
    }
}

try this:

using UnityEngine.UI;
[SerializeField] Text txtGoodLuck;

LeanTween.alphaText(txtGoodLuck.GetComponent<RectTransform>(), 1f , 1.5f);
Related