UGUI 打字机效果
程序员文章站
2022-06-22 20:02:07
...
挂载此脚本后运行,调用StartEffect方法,传入文本内容,即可实现打字机效果,文本内容可包含颜色标签。
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Text))]
public class TypeEffect : MonoBehaviour
{
public float TypeTimeSpace = 0.05f;//时间间隔
WaitForSeconds waitForSeconds;
Text text;
string content;
int count;
List<int> lst_start = new List<int>();
List<int> lst_end = new List<int>();
int colorIndex;
void Awake()
{
text = GetComponent<Text>();
waitForSeconds = new WaitForSeconds(TypeTimeSpace);
}
//开始打字
public void StartEffect(string content)
{
this.content = content;
lst_start.Clear();
lst_end.Clear();
int index_1 = content.IndexOf("<color=#");
while (index_1 >= 0 && index_1 < content.Length)
{
lst_start.Add(index_1);
index_1 = content.IndexOf("<color=#", index_1 + 1);
}
int index_2 = content.IndexOf("</color>");
while (index_2 >= 0 && index_2 < content.Length)
{
lst_end.Add(index_2);
index_2 = content.IndexOf("</color>", index_2 + 1);
}
text.text = "";
count = colorIndex = 0;
StringBuilder sb = new StringBuilder();
char[] array = content.ToCharArray();
StartCoroutine(Type(sb, array));
}
//强制终止打字
public void FinishEffect()
{
StopAllCoroutines();
text.text = content;
}
IEnumerator Type(StringBuilder sb, char[] array)
{
bool startColor = false;
while (count < array.Length)
{
if (lst_start.Count > 0 && count == lst_start[colorIndex])
{
for (int i = count; i < count + 18; i++)
{
sb.Append(array[i]);
}
sb.Append("</color>");
count += 18;
startColor = true;
}
else if (lst_end.Count > 0 && count == lst_end[colorIndex])
{
count += 8;
if (count < array.Length)
{
sb.Append(array[count++]);
}
colorIndex++;
startColor = false;
}
else
{
if (startColor)
{
sb.Replace("</color>", array[count++].ToString(), sb.Length - 8, 8);
sb.Append("</color>");
}
else
{
sb.Append(array[count++]);
}
}
text.text = sb.ToString();
yield return waitForSeconds;
}
//效果结束,想干嘛干嘛
}
}