1 using System; 2 using UnityEngine; 3 4 class UILine 5 { 6 GameObject targetObj; 7 LineRenderer lineRenderer; //LineRenderer渲染出的線段的兩個端點是3D世界中的點 8 int index = 0; 9 int poinCount = 0; //線段的端點數 10 Vector3 position; 11 12 public void Start(GameObject go, Color beginColor, Color endColor, float begineWidth, float endWidth) 13 { 14 targetObj = go; 15 if (null != targetObj) 16 { 17 targetObj.SetActive(true); 18 lineRenderer = targetObj.GetComponent<LineRenderer>(); 19 20 if (null == lineRenderer) 21 lineRenderer = targetObj.AddComponent<LineRenderer>(); 22 } 23 24 if (null != lineRenderer) 25 { 26 //顏色 27 lineRenderer.startColor = beginColor; 28 lineRenderer.endColor = endColor; 29 30 //寬度 31 lineRenderer.startWidth = begineWidth; 32 lineRenderer.endWidth = endWidth; 33 } 34 35 index = poinCount = 0; 36 } 37 38 public void Update() 39 { 40 if (Input.GetMouseButton(0)) 41 { 42 //屏幕坐標轉換為世界坐標 43 position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0f)); 44 //端點數+1 45 poinCount++; 46 //設置線段的端點數 47 lineRenderer.positionCount = poinCount; 48 49 //連續繪制線段 50 while (index < poinCount) 51 { 52 //兩點確定一條直線,所以我們依次繪制點就可以形成線段了 53 lineRenderer.SetPosition(index, position); 54 index++; 55 } 56 } 57 } 58 59 public static UILine BeginLine(GameObject go, Color beginColor, Color endColor, float beginWidth, float endWidth) 60 { 61 UILine line = new UILine(); 62 line.Start(go, beginColor, endColor, beginWidth, endWidth); 63 return line; 64 } 65 }