在有文字提示的時(shí)候,想要實(shí)現(xiàn)一個(gè)字一個(gè)字的往外面提示,
下面來介紹一下實(shí)現(xiàn)方式

面板中

方法一 使用計(jì)時(shí)器
TypewriterEffect .cs腳本
using UnityEngine;
using UnityEngine.UI;
public class TypewriterEffect : MonoBehaviour
{
public float charsPerSecond = 0.2f;//打字時(shí)間間隔
private string words;//保存需要顯示的文字
private bool isActive = false;
private float timer;//計(jì)時(shí)器
private Text myText;
private int currentPos = 0;//當(dāng)前打字位置
// Use this for initialization
void Start()
{
timer = 0;
isActive = true;
charsPerSecond = Mathf.Max(0.2f, charsPerSecond);
myText = GetComponent<Text>();
words = myText.text;
myText.text = "";//獲取Text的文本信息,保存到words中,然后動(dòng)態(tài)更新文本顯示內(nèi)容,實(shí)現(xiàn)打字機(jī)的效果
}
// Update is called once per frame
void Update()
{
OnStartWriter();
//Debug.Log (isActive);
}
//public void StartEffect()
//{
// isActive = true;
//}
/// <summary>
/// 執(zhí)行打字任務(wù)
/// </summary>
void OnStartWriter()
{
if (isActive)
{
timer += Time.deltaTime;
if (timer >= charsPerSecond)
{//判斷計(jì)時(shí)器時(shí)間是否到達(dá)
timer = 0;
currentPos++;
myText.text = words.Substring(0, currentPos);//刷新文本顯示內(nèi)容
if (currentPos >= words.Length)
{
OnFinish();
}
}
}
}
/// <summary>
/// 結(jié)束打字,初始化數(shù)據(jù)
/// </summary>
void OnFinish()
{
isActive = false;
timer = 0;
currentPos = 0;
myText.text = words;
}
}
方法二 使用DoTween插件
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
public class DoTxt : MonoBehaviour
{
public Text TxtTips;//text組件
public string str;//文字
public float time;//顯示時(shí)間
//想要首航縮進(jìn)的話,空格不好用
//①?gòu)?fù)制 這是兩個(gè)空白的字符,需要的自行復(fù)制
//②在腳本中直接賦值text是最簡(jiǎn)單的
//TextTest.text =“\u3000\u3000”+"字符串";
//2.UGUI的Text如果在編輯器直接輸入顯示我們可以自定義某幾個(gè)字符串的alpha值
// <color=#FFFFFF00>-----</color>
void Start()
{
TxtTips.DOText(str,time).SetEase(Ease.Linear);//勻速顯示當(dāng)前文章
}
}
```
### 方法三
```
private float letterPause = 0.2f;//等待時(shí)間
private string str;
public Text TxtTips;
public Text TxtTitle;
private IEnumerator TypeText(string text, Text txt)
{
_Introduce.clip = BgClips;//打字聲音
str = "";
foreach (char letter in text.ToCharArray())
{
str += letter;
//if (BgClips && !_Introduce.isPlaying)
//{
// _Introduce.Play ();
//}
yield return new WaitForSeconds(letterPause);
txt.text = str + "|";
_Introduce.Stop();//打字聲音暫停
}
txt.text = text;
}
```