!!!在实现以下效果之前,一定要往项目中导入DoTween插件。
一、搭建测试场景
1、在场景中新建一个带有Text组件的游戏物体A,并把这个游戏物体A中Text组件的Color属性中alpha值为0,让文字在场景中隐藏。
二、编写测试脚本
1、在项目中新建一个名为Test的测试脚本,并把以下代码复制到Test脚本中。
using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;public class Test : MonoBehaviour
{public Text text_piaozi;GameObject go;Sequence mySequence;void Update(){if (Input.GetKeyDown(KeyCode.Space)){FlyTo();}}public void FlyTo(){if (go != null){Destroy(go?.gameObject);// 取消序列 if (mySequence != null && mySequence.IsActive()){mySequence.Kill();Debug.Log("Sequence has been killed.");}}go = GameObject.Instantiate(text_piaozi.gameObject, text_piaozi.transform.parent);Debug.Log(go);Graphic graphic = go.GetComponent<Text>();RectTransform rt = graphic.rectTransform;Color c = graphic.color;c.a = 0;graphic.color = c;mySequence = DOTween.Sequence();Tweener move1 = rt.DOMoveY(rt.position.y + 50, 0.5f);Tweener move2 = rt.DOMoveY(rt.position.y + 100, 0.5f);Tweener alpha1 = graphic.DOColor(new Color(c.r, c.g, c.b, 1), 0.5f);Tweener alpha2 = graphic.DOColor(new Color(c.r, c.g, c.b, 0), 0.5f);mySequence.Append(move1);mySequence.Join(alpha1);mySequence.AppendInterval(1);mySequence.Append(move2);mySequence.Join(alpha2);mySequence.OnComplete(() => { Destroy(graphic.gameObject); });}
}
2、保存上述代码后,回到Unity项目中,把这个Test测试脚本挂到游戏中任意一个游戏物体上面,然后把我们的飘字模板Text (Legacy)游戏物体拖拽到Test测试脚本中的Text_piaozi引用上面。
三、测试
1、运行游戏,然后按下键盘的空格键,飘字就会出现。