Unity Text文本要實(shí)現(xiàn)打字機(jī),即一個(gè)個(gè)文字出來的效果,可以通過代碼把text文本字符串拆成一個(gè)個(gè)字符然后添加到文本中。
具體實(shí)現(xiàn):
新建一個(gè)控制腳本:TypewriteController.cs,并編寫以下代碼:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TypewriteController : MonoBehaviour
{
public float typingSpeed = 0.1f; // 每個(gè)字符的顯示間隔時(shí)間
private string fullText;
private string currentText = "";
public Text textComponent;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.A))
{
fullText = textComponent.text;
textComponent.text = "";
StartCoroutine(TypeText());
}
}
IEnumerator TypeText()
{
foreach (char c in fullText)
{
currentText += c;
textComponent.text = currentText;
yield return new WaitForSeconds(typingSpeed);
}
}
}
此控制腳本先把腳本文本獲取后賦給一個(gè)字符串變量,然后置空文本內(nèi)容,再通過協(xié)程把該字符串變量值拆分成一個(gè)個(gè)字符,然后使用協(xié)程來把一個(gè)個(gè)字符(即單個(gè)文字) 賦值給文本,這樣就完成了打字機(jī)的效果。
新建一個(gè)場(chǎng)景,并在場(chǎng)景創(chuàng)建一個(gè)Text組件,把腳本拉到場(chǎng)景中,再把Text組件拖到腳本中的textComponent對(duì)象,運(yùn)行場(chǎng)景,效果如下:文章來源:http://www.zghlxwxcb.cn/news/detail-822588.html
Unity Text文本實(shí)現(xiàn)打字機(jī)(一個(gè)一個(gè)出來)的效果文章來源地址http://www.zghlxwxcb.cn/news/detail-822588.html
到了這里,關(guān)于Unity Text文本實(shí)現(xiàn)打字機(jī)(一個(gè)一個(gè)出來)的效果的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!