關於UGUI之修改Text字間距
阿新 • • 發佈:2019-02-11
using UnityEngine; using System.Collections; using UnityEngine.UI; using System; using System.Collections.Generic; using System.IO; using System.Text; [AddComponentMenu("UI/Effects/TextSpacing")] public class TextSpacing : BaseMeshEffect { //Font public string Font = ""; //數字間隔 public float _textSpacing = 1f; //字元預設 size //[SerializeField] public float DefaultSize = 32f; //字元當前 size public float CurrentSize = 32f; public override void ModifyMesh(VertexHelper vh) { if (!IsActive() || vh.currentVertCount == 0) { return; } List<UIVertex> vertexs = new List<UIVertex>(); vh.GetUIVertexStream(vertexs); int indexCount = vh.currentIndexCount; Debug.Log("Bug測試" + indexCount+" --- "+ gameObject.GetComponent<Text>().text); UIVertex vt; for (int i = 6; i < indexCount; i++) { //第一個字不用改變位置 vt = vertexs[i]; vt.position += new Vector3(_textSpacing * (i / 6), 0, 0); vertexs[i] = vt; //以下注意點與索引的對應關係 if (i % 6 <= 2) { vh.SetUIVertex(vt, (i / 6) * 4 + i % 6); } if (i % 6 == 4) { vh.SetUIVertex(vt, (i / 6) * 4 + i % 6 - 1); } } if (DefaultSize == 0) { gameObject.transform.localScale = Vector3.one; } else { gameObject.transform.localScale = new Vector3(CurrentSize / DefaultSize, CurrentSize / DefaultSize, CurrentSize / DefaultSize); } Font = gameObject.GetComponent<Text>().font.name; } }
以上內容借鑑UGUI之修改Text字間距,一個字元會生成6個頂點,6個頂點構成2個三角面
以上內容借鑑UGUI Text富文字的頂點數優化using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UI; public class UIVertexOptimize : BaseMeshEffect { struct Triangle { public UIVertex v1; public UIVertex v2; public UIVertex v3; } List<UIVertex> verts = new List<UIVertex>(); public override void ModifyMesh(VertexHelper vh) { vh.GetUIVertexStream(verts); Debug.Log(verts.Count); OptimizeVert(ref verts); Debug.Log(verts.Count); vh.Clear(); vh.AddUIVertexTriangleStream(verts); } void OptimizeVert(ref List<UIVertex> vertices) { List<Triangle> tris = new List<Triangle>(); for (int i = 0; i < vertices.Count - 3; i += 3) { tris.Add(new Triangle() { v1 = vertices[i], v2 = vertices[i + 1], v3 = vertices[i + 2] }); } vertices = tris.Distinct().SelectMany(tri => new[]{ tri.v1, tri.v2, tri.v3 }).ToList(); } }
注意若Text掛在 修改間距指令碼的同時新增OutLine元件,指令碼在上OutLine元件在下,不然會發生越界,(好像是OutLine元件會將文字定點數乘以5)