跟的教程是比较早的,14年录制的一套视频。教程中使用的NGUI。关于其中用HUDText制作伤害冒字的效果。扫了一眼ngui的HUDText.cs,没有耐心阅读(超过两百行,不想阅读了),因此使用TextMeshPro这个UI控件制作该效果(也可以使用Text制作。用TextMeshPro的原因,是因为之前很少用到,在这里换个新的控件试试)。
关于TextMeshPro与Text两者的异同,请看这一篇博客:http://mot.ttthyy.com/424.html
先创建一个TextMeshPro控件,将其制作成一个预设体,然后将脚本挂载在一个GameObject上(随便什么都可以):
using UnityEngine;
using TMPro;
using System.Collections;
public class HUDTextMeshPro : MonoBehaviour
{
public TextMeshProUGUI textPrefab; // TextMeshPro 的预制体
public Transform canvasTransform; // Canvas 的 Transform
public float displayDuration = 2f; // 文本显示持续时间
public float fadeDuration = 1f; // 渐变动画持续时间
private void Start()
{
// 确保预制体和 Canvas 都已指定
if (textPrefab == null || canvasTransform == null)
{
Debug.LogError("Please assign TextPrefab and CanvasTransform in the inspector!");
return;
}
ShowText(transform.position, "hello world", Color.blue);
}
// 在指定位置显示文本
public void ShowText(Vector3 position, string message, Color textColor)
{
// 创建 TextMeshPro 对象
TextMeshProUGUI textInstance = Instantiate(textPrefab, canvasTransform);
textInstance.transform.position = position;
// 设置文本内容和颜色
textInstance.text = message;
textInstance.color = textColor;
// 启动渐变动画
StartCoroutine(FadeOutText(textInstance));
}
// 渐变动画
private IEnumerator FadeOutText(TextMeshProUGUI text)
{
float timer = 0f;
while (timer < displayDuration)
{
// 计算当前 alpha 值
float alpha = Mathf.Lerp(1f, 0f, timer / fadeDuration);
// 更新文本 alpha 值
text.color = new Color(text.color.r, text.color.g, text.color.b, alpha);
timer += Time.deltaTime;
yield return null;
}
// 销毁文本对象
Destroy(text.gameObject);
}
}
运行效果:
该脚本提供的方法在每次调用后都先创建再销毁,可以考虑使用对象池。每次调用后不是销毁,而是禁用,然后再调用ShowText方法时,再启用TextMeshPro(如果使用Text制作该效果,则启用Text)。这样避免内存占用造成资源浪费。