unity实现打字机效果
实现思路: 做一个定时器,每次达到时间更新一次Text
方法二: 导入Dotween,text.DoText(“XXX”,5f)
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Text))]
public class TypewriterEffect : MonoBehaviour
{
private float intervalTime = 0.2f;//打字时间间隔
private string words;//保存需要显示的文字
private bool isActive = false;
private float timer;//计时器
private Text myText;
private int currentPos = 0;//当前打字位置
private System.Action finishCallBack;
void Awake()
{
//timer = 0;
//isActive = true;
//intervalTime = Mathf.Max(0.2f, intervalTime);
//words = myText.text;
myText = GetComponent<Text>();
myText.text = "";
}
void Update()
{
if (isActive)
{
UpdateWorldWrite();
}
}
/// <summary>
/// 更新打字效果
/// </summary>
void UpdateWorldWrite()
{
if (isActive)
{
timer += Time.unscaledDeltaTime;
if (timer >= intervalTime)
{//判断计时器时间是否到达
timer = 0;
currentPos++;
myText.text = words.Substring(0, currentPos);//刷新文本显示内容
if (currentPos >= words.Length)
{
OnFinish();
}
}
}
}
/// <summary>
/// 结束打字,初始化数据
/// </summary>
void OnFinish()
{
isActive = false;
timer = 0;
currentPos = 0;
myText.text = words;
if (this.finishCallBack != null)
this.finishCallBack();
}
/// <summary>
/// 外部调用接口
/// </summary>
/// <param name="text">显示文字</param>
/// <param name="_intervalTime">间隔时间</param>
/// <param name="finishCallBack">动画完成回调</param>
public void ShowText(string _text, float _intervalTime, System.Action _finishCallBack)
{
this.finishCallBack = _finishCallBack;
timer = 0;
currentPos = 0;
intervalTime = Mathf.Max(0.2f, _intervalTime);
words = _text;
if (myText != null)
myText.text = "";
if (!string.IsNullOrEmpty(_text))
{
isActive = true;
}
}
}
本文地址:https://blog.csdn.net/qq_34937637/article/details/107897411