using UnityEngine.UI; //文本的使用要引用新的名称空间
public class ReadText : MonoBehaviour
{
[Header("渐变颜色")]
public string color = "red";
[Header("渐变时间间隔")]
public float interval = 0.3f;
[Header("打字机动画开关")]
public bool animationPlayer = false;
private string head; //添加在文本头部的字符串
private string end; //在需要改变颜色的字符后
private Text m_Text; //需要用到的文本对象
private float timer; //计时器
private int index = 0; //改变颜色的字符数
//原始文本
private string originText; //接受最初的文本
private void Awake()
{
m_Text = GetComponent<Text>(); //获取文本组件
}
private void Start()
{
head = "<color=" + color + ">"; //头部代码
end = "</color>"; //结尾处代码
originText = m_Text.text; //文本内容
}
private void Update()
{
if (animationPlayer)
{
timer += Time.deltaTime; //计时器计时
if (timer > interval) //计时器大于时间间隔
{
//What's your name?
if (index < originText.Length) //检测是否已经到了字符串最后
{
//检测到空格直接跳过
while (originText[index] == ' ')
{
index++;
}
//先插入尾标签
m_Text.text = originText.Insert(++index, end);
//再插入头标签
m_Text.text = m_Text.text.Insert(0, head);
//计时器归零
timer = 0;
}
}
}
}
}
Unity学习笔记——UI文本逐个字符变色
最新推荐文章于 2021-12-30 21:33:10 发布