LineRenderer实现一个画线组件
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 }