XRText.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using DG.Tweening;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. using UnityEngine.EventSystems;
  7. using UnityEngine.UI;
  8. using XRTool.Util;
  9. namespace XRTool.WorldUI
  10. {
  11. public class XRText : Text
  12. {
  13. [Range(-10f,100f)]
  14. public float textSpacing = 0f;
  15. protected override void OnPopulateMesh(VertexHelper vh)
  16. {
  17. base.OnPopulateMesh(vh);
  18. if (!IsActive() || vh.currentVertCount == 0)
  19. {
  20. return;
  21. }
  22. Text text = GetComponent<Text>();
  23. if (text == null)
  24. {
  25. Debug.LogError("Missing Text component");
  26. return;
  27. }
  28. List<UIVertex> vertexs = new List<UIVertex>();
  29. vh.GetUIVertexStream(vertexs);
  30. int indexCount = vh.currentIndexCount;
  31. string[] lineTexts = text.text.Split('\n');
  32. Line[] lines = new Line[lineTexts.Length];
  33. //根据lines数组中各个元素的长度计算每一行中第一个点的索引,每个字、字母、空母均占6个点
  34. for (int i = 0; i < lines.Length; i++)
  35. {
  36. //除最后一行外,vertexs对于前面几行都有回车符占了6个点
  37. if (i == 0)
  38. {
  39. lines[i] = new Line(0, lineTexts[i].Length + 1);
  40. }
  41. else if (i > 0 && i < lines.Length - 1)
  42. {
  43. lines[i] = new Line(lines[i - 1].EndVertexIndex + 1, lineTexts[i].Length + 1);
  44. }
  45. else
  46. {
  47. lines[i] = new Line(lines[i - 1].EndVertexIndex + 1, lineTexts[i].Length);
  48. }
  49. }
  50. UIVertex vt;
  51. for (int i = 0; i < lines.Length; i++)
  52. {
  53. for (int j = lines[i].StartVertexIndex + 6; j <= lines[i].EndVertexIndex; j++)
  54. {
  55. if (j < 0 || j >= vertexs.Count)
  56. {
  57. continue;
  58. }
  59. vt = vertexs[j];
  60. vt.position += new Vector3(textSpacing * ((j - lines[i].StartVertexIndex) / 6), 0, 0);
  61. vertexs[j] = vt;
  62. //以下注意点与索引的对应关系
  63. if (j % 6 <= 2)
  64. {
  65. vh.SetUIVertex(vt, (j / 6) * 4 + j % 6);
  66. }
  67. if (j % 6 == 4)
  68. {
  69. vh.SetUIVertex(vt, (j / 6) * 4 + j % 6 - 1);
  70. }
  71. }
  72. }
  73. }
  74. }
  75. }