using UnityEngine; using System.Collections; using UnityEngine.UI; using System.Collections.Generic; internal class Line { //每行開始頂點索引 private int startVertexIndex; public int StartVertexIndex { get { return startVertexIndex; } } //每行結束頂點索引 private int endVertexIndex; public int EndVertexIndex { get { return endVertexIndex; } } //每行頂點總量 private int countVertexIndex; public int CountVertexIndex { get { return countVertexIndex; } } public Line(int startVertexIndex, int countVertexIndex) { this.startVertexIndex = startVertexIndex; this.countVertexIndex = countVertexIndex; this.endVertexIndex = this.startVertexIndex + countVertexIndex - 1; } } /// <summary> /// 這是設置字體移動的核心類 /// 執行多重行移動的核心算法是:將多重行分開依次進行處理,每一行的處理都是前面對單行處理的子操做 /// 可是由vh是記錄一個文本中全部的字的頂點,因此說須要分清楚每行開始,每行結束,以及行的字個數, /// 如此須要建立一個行的數據結構,以保存這些信息 /// </summary> [AddComponentMenu("UI/Effects/TextSpacing")] public class TextSpacing : BaseMeshEffect { public float spacing = 0; public override void ModifyMesh(VertexHelper vh) { Text text = GetComponent<Text>(); string[] ls = text.text.Split('\n'); int length = ls.Length; bool isNewLine = false; Line[] line; if (string.IsNullOrEmpty(ls[ls.Length - 1]) == true) { line = new Line[length - 1]; isNewLine = true; } else { line = new Line[length]; } //Debug.Log("ls長度" + ls.Length); for (int i = 0; i < line.Length; i++) { if (i == 0 && line.Length == 1 && isNewLine == false)//解決單行時沒有換行符的狀況 { line[i] = new Line(0, ls[i].Length * 6); break; } if (i == 0 && line.Length >= 1)//解決單行時有換行符的狀況,以及多行時i爲0的狀況 { line[i] = new Line(0, (ls[i].Length + 1) * 6); } else { if (i < line.Length - 1) { line[i] = new Line(line[i - 1].EndVertexIndex + 1, (ls[i].Length + 1) * 6); } else { if (isNewLine == true)//解決多行時,最後一行末尾有換行符的狀況 { line[i] = new Line(line[i - 1].EndVertexIndex + 1, (ls[i].Length + 1) * 6); } else { line[i] = new Line(line[i - 1].EndVertexIndex + 1, ls[i].Length * 6); } } } } List<UIVertex> vertexs = new List<UIVertex>(); vh.GetUIVertexStream(vertexs); int countVertexIndex = vertexs.Count; //Debug.Log("頂點總量" + vertexs.Count); for (int i = 0; i < line.Length; i++) { if (line[i].CountVertexIndex == 6) { continue; } for (int k = line[i].StartVertexIndex + 6; k <= line[i].EndVertexIndex; k++) { UIVertex vertex = vertexs[k]; vertex.position += new Vector3(spacing * ((k - line[i].StartVertexIndex) / 6), 0, 0); //Debug.Log("執行"); vertexs[k] = vertex; if (k % 6 <= 2) { vh.SetUIVertex(vertex, (k / 6) * 4 + k % 6); } if (k % 6 == 4) { vh.SetUIVertex(vertex, (k / 6) * 4 + k % 6 - 1); } } } } }