之前在網上找過各種的逐個輸出字,我可能理解能力不好,照着代碼復制沒有能使用成功,於是自己研究了很多網上說的思路,各種改良出了一個能用的,寫完自己測試,覺得還真好用,於是記錄下來
用法:將用代碼組件掛上去,通過查找到代碼組件,通過enabled來控制組件開關,每次更新文字時候,讓組件進行一次關閉和開啟,就能再次逐個顯示
using UnityEngine; using System.Collections; using UnityEngine.UI; public class WordOutPut : MonoBehaviour { public float charsPerSecond = 0.05f;//打字時間間隔 private string words;//保存需要顯示的文字 private bool isActive = false; //判斷是否開始輸出 private float timer;//計時器 private Text myText;//獲取身上的test腳本 private int currentPos = 0;//當前打字位置 // Use this for initialization private void OnDisable() { OnFinish();//當腳本在失活的時候,將數據進行重置 } /// <summary>
/// 當腳本被激活的時候,將數據進行初始化
/// </summary> private void OnEnable() { timer = 0; isActive = true; charsPerSecond = Mathf.Max(0.02f, charsPerSecond); //將最小的出字速度限制為0.02,也可以自行調整 myText = GetComponent<Text>(); words = myText.text; myText.text = "";//獲取Text的文本信息,保存到words中,然后動態更新文本顯示內容,實現打字機的效果 } void Start() { } // Update is called once per frame void Update() { OnStartWriter(); //Debug.Log (isActive); } /// <summary> /// 執行打字任務 /// </summary> void OnStartWriter() { if (isActive) { timer += Time.deltaTime; if (timer >= charsPerSecond)//判斷計時器時間是否到達 { timer = 0; currentPos++;
//這里其實還可以做一個改良,可以檢測一個input用戶輸入,如果輸入了,則讓currentPos = words.Length,這樣可以實現按下按鍵,馬上就顯示完畢
myText.text = words.Substring(0, currentPos);//刷新文本顯示內容 if (currentPos >= words.Length) { OnFinish(); } } } } /// <summary> /// 結束打字,初始化數據 /// </summary> void OnFinish() { isActive = false; timer = 0; currentPos = 0; myText.text = words; } }