UI里有一个现成的脚步可以给Text的文字设置为打字机的效果,而UGUI并没有给我们提供这个方法。
所以下面脚本用来实现这个功能。

效果如下;

UGUI文本打字机效果_UI

实现方法非常简单,直接把下面脚本绑定到Text文本上就可以。

脚本:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Typewriter : MonoBehaviour
{

public float TypeSpeed = 0.2f;//打字速度
Text Showtext;
string sContent="天间夜色凉如水,卧看牵牛织女星。";//文本内容字符串
int curPos;//当前文字位置(当前的最后一个字)
void Start()
{
Showtext =this. GetComponent<Text>();
SetContent();
}
void SetContent()
{
curPos = 0;

Debug.Log("文本内容:" + sContent.Length);
Showtext.text = string.Empty;
InvokeRepeating("Typing", 0, TypeSpeed);
}

void Update()
{

}

void Typing()
{
if (sContent.Length - 1 == curPos)//如果当前字符位置等于字符总长度前一个位置就停止调用打字方法
CancelInvoke("Typing");


if (curPos < sContent.Length)
{
Showtext.text += sContent.Substring(curPos, 1);//每次都截取到当前位置的下一个字符位置
curPos++;
}


}

}