如何使用 LeanTween 淡入淡出 TextMesh alpha?

How to fade TextMesh alpha with LeanTween?

我一直在寻找一种在 Unity 中淡化 TextMesh-Text 的 alpha 值的方法,但我无法在线或在 LeanTween Documentation 中找到解决方案。

我想出了自己的解决方案。

我没有直接更改 TextMesh-Component 的 alpha,而是向包含我的 TextMesh-Component 的游戏对象添加了一个 CanvasGroup。然后我改为操纵 CanvasGroup 的 alpha 值。

要使用我的示例代码:

  1. 在你的 Canvas 上:[RightClick] > UI > Text - TextMeshPro
  2. 将我的示例脚本附加到此游戏对象。 (这会自动创建所需的 Canvas 组)
  3. 按播放键 (Ctrl + P)

延迟 2 秒后(因为 of.setDelay(2f) 文本应该淡入。

示例代码:

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);
    }
}

在简要浏览了 API 之后,我猜想一个比引入 CanvasGroups 只是为了淡化单个文本更好的方法是使用 LeanTwean.value for setting its colorCanvasGroup 在我看来有点矫枉过正。

(示例取自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;
}

您还可以使用以下行扩展 LeanTween 扩展方法文件 (LeanTweenExt.cs)。此方法将允许您在文本网格上应用 LeanAlphaText,就像您以前在 UI 文本上所做的那样。

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;
}