UGUI 打字機效果

掛載此腳本後運行,調用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;
		}
		//效果結束,想幹嘛幹嘛
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章