using System; using UnityEngine; using System.Collections; using UnityEngine.UI; public class Typewriter : MonoBehaviour { /// /// 打字速度 /// public float TypeSpeed = 0.2f; public Text Showtext; /// /// 文本内容字符串 /// public string StringContent = ""; /// /// 当前文字位置(当前的最后一个字) /// private int curPos; void Awake() { Showtext = this.GetComponent(); } private void Start() { } [ContextMenu("SetContent")] /// /// 设置内容 /// public void SetContent() { StringContent = Showtext.text; curPos = 0; Debug.Log("文本内容:" + StringContent.Length); Showtext.text = string.Empty; InvokeRepeating("Typing", 0, TypeSpeed); } public void Pause() { CancelInvoke("Typing"); } void Typing() { if (StringContent.Length - 1 == curPos) //如果当前字符位置等于字符总长度前一个位置就停止调用打字方法 CancelInvoke("Typing"); if (curPos < StringContent.Length) { Showtext.text += StringContent.Substring(curPos, 1); //每次都截取到当前位置的下一个字符位置 curPos++; } } }