用DoTween实现打字效果

最近在研究DoTween插件,想做个打字效果,一开始用普通的Text,这个用DoText做比较简单。但是新版的Unity已经默认TextMestPro,常用的Text组件已经在Legacy里了,后面会慢慢淘汰吧。在Dotween官网没找到TextMeshPro相关的案例,百度了下做了个简单的demo。

先说Text打字效果:

在Unity里面新建个Text,然后把下面的代码挂到Text组件上就可以了:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.UI;

public class TextType : MonoBehaviour
{

    Text normalText;

    // Start is called before the first frame update
    void Start()
    {

        normalText = GetComponent<Text>();
        //要打出的文字
        string str = "Put the text you want to show here";
        //DoText 第一个参数是上面要打出的文字,第二个是时间
        normalText.DOText(str, 1.5f).SetEase(Ease.Linear);

    }

}

下面是Unity中的效果:TextMeshPro用DoText行不通,用DoTween.To()可以实现:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
using UnityEngine.UI;
using TMPro;
public class TextType : MonoBehaviour
{

    TextMeshProUGUI tmp;
    private TMP_Text myTextMeshProTextField;
    Text normalText;

    // Start is called before the first frame update
    void Start()
    {
        //获取TextMeshPro组件
        tmp = GetComponent<TextMeshProUGUI>();
        //获取要打出的文字,这里可以在Unity里排版好
        string tmpText = tmp.text;
        //打字效果,前面设置为空,后面tmpText 参数是要打的文字内容,最后一个是打字时间
        DOTween.To(()=>string.Empty,value=>tmp.text=value,tmpText,3f).SetEase(Ease.Linear);
    }

}

TextMeshPro打字效果:

另外要用到官网的其他方法的话要开启支持TextMeshPro选项,要在Tools - Demigiant - DOTween Utility Panel - Setup DOTween...窗口中勾选TMP,不然写代码的时候像DOTweenTMPAnimator这些就会报错。

记录一下,以免忘了呀。

猜你喜欢

转载自blog.csdn.net/zsqf813/article/details/134164191