在 Unity 中实现“打字机效果”(Typewriter Effect),用于逐字显示文本,营造出像是打字机逐字打出文字的效果
使用 UnityEngine.UI 的 Text 实现(适用于旧版 UI)
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class TypewriterEffect : MonoBehaviour
{
public Text targetText; // 要应用打字机效果的 Text 组件
public float typingSpeed = 0.05f; // 每个字符之间的间隔时间(秒)
private string fullText;
private bool isTyping = false;
void Start()
{
if (targetText == null)
targetText = GetComponent<Text>();
if (targetText != null)
{
fullText = targetText.text;
targetText.text = "";
StartTyping();
}
}
public void StartTyping()
{
if (!isTyping)
{
StartCoroutine(TypeText());
}
}
IEnumerator TypeText()
{
isTyping = true;
targetText.text = "";
foreach (char c in fullText.ToCharArray())
{
targetText.text += c;
yield return new WaitForSeconds(typingSpeed);
}
isTyping = false;
}
// 可选:立即显示全部文本
public void SkipTyping()
{
StopAllCoroutines();
targetText.text = fullText;
isTyping = false;
}
}
使用 TextMeshPro(推荐,功能更强)
using UnityEngine;
using TMPro;
using System.Collections;
public class TypewriterEffectTMP : MonoBehaviour
{
public TMP_Text targetText;
public float typingSpeed = 0.05f;
private string fullText;
private bool isTyping = false;
void Start()
{
if (targetText == null)
targetText = GetComponent<TMP_Text>();
if (targetText != null)
{
fullText = targetText.text;
targetText.text = "";
StartTyping();
}
}
public void StartTyping()
{
if (!isTyping)
{
StartCoroutine(TypeText());
}
}
IEnumerator TypeText()
{
isTyping = true;
targetText.text = "";
foreach (char c in fullText.ToCharArray())
{
targetText.text += c;
yield return new WaitForSeconds(typingSpeed);
}
isTyping = false;
}
public void SkipTyping()
{
StopAllCoroutines();
targetText.text = fullText;
isTyping = false;
}
}

Comments NOTHING