using UnityEngine; using TMPro; //距离单位 public enum UnitType { mm = 1000, //毫米 cm = 100, //厘米 dm = 10, //分米 m = 1, //米 } //[ExecuteInEditMode] public class Line : MonoBehaviour { public GameObject StObj, EdObj; TextMesh tm; LineRenderer line; [Header("实时绘制(较多会卡顿)")] public bool IsRt = false; [Header("线的粗细")] public float LineWidth = 0.05f; [Header("划线材质球")] public Material LineMat; [Header("线的颜色")] public Color LineColor; [Header("长度单位")] public UnitType unittype = UnitType.cm; Transform tram; private void Start() { //LineMat = new Material(Shader.Find("Standard")); CreateTm(); CreateLine(); } void CreateTm() { tram = transform.Find("tm"); if (tram != null) tm = tram.GetComponent(); if (tm == null) { tm = new GameObject("tm").AddComponent(); tm.color = Color.white; tm.fontSize = 20; tm.transform.SetParent(this.transform); tm.characterSize = 0.1f; //tm.GetComponent().sizeDelta = new Vector2(2, 1); //tm.alignment = TextAlignmentOptions.Center; } } void CreateLine() { line = gameObject.GetComponent(); if (line == null) line = gameObject.AddComponent(); line.material = LineMat; } public void DrawLineInfo() { tm.text = (Vector3.Distance(StObj.transform.position, EdObj.transform.position) * (int)unittype).ToString("F1") + unittype; tm.transform.position = (StObj.transform.position + EdObj.transform.position) / 2 + new Vector3(0, 0.1f, 0); line.SetPositions(new Vector3[] { StObj.transform.position, EdObj.transform.position }); line.startWidth = LineWidth; line.endWidth = LineWidth; LineMat.color = LineColor; } void Update() { if (IsRt) DrawLineInfo(); } }