unity中實現鍵盤打字的效果
阿新 • • 發佈:2019-01-30
UI中的設定如圖所示:
其中Text指令碼中的程式碼如下所示:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
public class text:MonoBehaviour
{
public float charsPerSecond=0.2f;//打字間隔的時間
private string words;//儲存需要顯示的文字
private bool isActive=false;
private float timer;//計時器
private Text myText;
private int currentPos=0 ;
private AudioSource keyAudio;
private void Start()
{
timer=0f;
isActive=true;
charsPerSecond=Mathf.Max(0.2f,charsPerSecond);
myText=GetComponent<Text>();
//獲取Text的文字資訊,儲存到words中,然後動態更新文字
//顯示的內容,實現打字機的效果
myText.text="";
keyAudio=GetComponent<AudioSource>();
}
private void Update()
{
OnStartWriter();
}
public void StartEffect()
{
isActive=true;
}
//執行打字任務
private void OnStartWriter()
{
if (isActive)
{
timer+=Time.deltaTime;
if(timer>=charsPerSecond)
{
timer=0f;
currentPos++;
//重新整理文字顯示內容
myText.text=words.Substring(0,currentPos);
keyAudio.Play();
if(currentPos>=words.Length)
{
OnFinish();
keyAudio.Stop();
}
}
}
}
//結束打字,初始化資料
private void OnFinish()
{
isActive=false;
timer=0 ;
currentPos=0;
myText.text=words;
}
}