1.需要改脚本挂载Text组件之上
2.所用知识点:string中的Substring–两个参数,第一个参数为初始下标,第二个为终止下标,从某个字符串中剪切出冲初始下标到终止下标中间的字符,重新组成一个字符串
3.补充知识:Math.Max返回两个或多个数中的最大值,反之,Math.Min返回两个或多数之间的最小数
4.代码
日期:2020/11/20 16:56:23
功能:打字机功能
*****************************************************/
using UnityEngine;
using UnityEngine.UI;
public class TxtTools : MonoBehaviour
{
[Header("打字间隔")]public float typeTimer=0.2f;
[Header("打字的内容")]public string words;
private Text txtFile;
private bool isStartTyping=true;//是否开始打字
private float timer;
private int currentIndex = 0;
private void Start()
{
txtFile = GetComponent<Text>();
//返回两个或多个值中最大的值
typeTimer = Mathf.Max(0.02f, typeTimer);
}
private void Update()
{
OnStartTyping();
}
private void OnStartTyping()
{
if (isStartTyping)
{
timer += Time.deltaTime;
if (timer >= typeTimer)
{
timer = 0;
currentIndex++;
txtFile.text = words.Substring(0,currentIndex);
if (currentIndex>=words.Length)
{
OnFinshTyping();
}
}
}
}
private void OnFinshTyping()
{
isStartTyping = false;
timer = 0;
currentIndex = 0;
txtFile.text = words;
}
}
5.效果图: