Ruler.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System.Threading.Tasks;
  2. using System.Net.Http.Headers;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. using System.Linq;
  7. using UnityEngine.UI;
  8. namespace Rokid.UXR.Components {
  9. [ExecuteInEditMode]
  10. public class Ruler : MonoBehaviour
  11. {
  12. /// <summary>
  13. /// 缓存直尺的刻度
  14. /// </summary>
  15. /// <typeparam name="int"></typeparam>
  16. /// <typeparam name="GameObject"></typeparam>
  17. /// <returns></returns>
  18. public Dictionary<int, GameObject> dialDict = new Dictionary<int, GameObject>();
  19. /// <summary>
  20. /// 直尺长度
  21. /// </summary>
  22. [Range(1, 15)]
  23. public int length = 1;
  24. /// <summary>
  25. /// 直尺刻度显示
  26. /// </summary>
  27. public GameObject tempDial;
  28. public Transform ruler;
  29. private float oldLength;
  30. private void Update()
  31. {
  32. if (oldLength != length)
  33. {
  34. oldLength = length;
  35. //更新直尺长度
  36. ShowDial(length);
  37. ruler.transform.localScale = new Vector3(0.4f, length, 1);
  38. }
  39. }
  40. /// <summary>
  41. /// 显示直尺的刻度
  42. /// </summary>
  43. private void ShowDial(int length)
  44. {
  45. foreach (var item in dialDict.Values)
  46. {
  47. if (item == null || item.gameObject == null)
  48. continue;
  49. item.gameObject.SetActive(false);
  50. }
  51. for (int i = 1; i < length; i++)
  52. {
  53. if (dialDict.ContainsKey(i) && dialDict[i].gameObject != null)
  54. {
  55. dialDict[i].gameObject.SetActive(true);
  56. }
  57. else
  58. {
  59. //先查找是否已经实例化tip如果
  60. Transform tsf = transform.Find(i + "m");
  61. if (tsf != null)
  62. {
  63. if (dialDict.ContainsKey(i))
  64. {
  65. dialDict[i] = tsf.gameObject;
  66. }
  67. else
  68. {
  69. dialDict.Add(i, tsf.gameObject);
  70. }
  71. return;
  72. }
  73. GameObject go = GameObject.Instantiate(tempDial, new Vector3(0, 0.001f, i), Quaternion.Euler(90, 0, 0));
  74. go.SetActive(true);
  75. go.transform.SetParent(this.transform);
  76. go.transform.localPosition = new Vector3(0, 0.001f, i);
  77. if (dialDict.ContainsKey(i))
  78. {
  79. dialDict[i] = go;
  80. }
  81. else
  82. {
  83. dialDict.Add(i, go);
  84. }
  85. go.GetComponentInChildren<Text>().text = i + "m";
  86. go.name = i + "m";
  87. }
  88. }
  89. }
  90. }
  91. }