新建一个脚本,这个物体得挂在有摄像机组件的物体上才能生效
OnPostRender() 这个函数才会被自动调用(类似生命周期自动调用)
然后就可以代码画线了,原理是openGL的画线
1using UnityEngine; 2using System.Collections; 3using System.Collections.Generic; 4 5/// <summary> 6/// GL画图 7/// </summary> 8public class GLDraw : UnityNormalSingleton<GLDraw> { 9 10 public Transform p1; 11 public Transform p2; 12 private List<Vector2> pointList; 13 private bool isOpen; 14 15 private Material mat; 16 private Shader shader; 17 18 private void Start() 19 { 20 pointList = new List<Vector2>(); 21 shader = Shader.Find("Unlit/Color"); 22 mat = new Material(shader); 23 mat.SetColor("Main Color", Color.black); 24 } 25 26 public void DrawLine(List<object> list) 27 { 28 pointList.Clear(); 29 for (int i = 0; i < list.Count; i++) 30 { 31 Vector2 screenPos = (Vector2)list[i]; 32 pointList.Add(new Vector2(screenPos.x, Screen.height - screenPos.y)); 33 } 34 } 35 36 public void ShowLine(bool b) 37 { 38 isOpen = b; 39 } 40 41 void OnPostRender() 42 { 43 if (!isOpen) 44 { 45 return; 46 } 47 48 //mat = new Material(Shader.Find("Unlit/Color")); 49 //Debug.Log("调用"); 50 //if (!mat) 51 //{ 52 // Debug.LogError("Please Assign a material on the inspector"); 53 // return; 54 //} 55 GL.PushMatrix(); //保存当前Matirx 56 mat.SetPass(0); //刷新当前材质 57 GL.LoadPixelMatrix();//设置pixelMatrix 58 GL.Color(Color.yellow); 59 GL.Begin(GL.LINES); 60 61 //画2次,奇偶数画连续折线法 62 for (int i = 0; i < pointList.Count; i++) 63 { 64 GL.Vertex3(pointList[i].x, pointList[i].y, 0); 65 } 66 for (int i = 1; i < pointList.Count; i++) 67 { 68 GL.Vertex3(pointList[i].x, pointList[i].y, 0); 69 } 70 //单次画线发 71 //GL.Vertex3(0, 0, 0);//GL.Vertex3(Screen.width, Screen.height, 0); 72 //固定2点画 73 //GL.Vertex3(p1.position.x, p1.position.y, 0); 74 //GL.Vertex3(p2.position.x, p2.position.y, 0); 75 GL.End(); 76 GL.PopMatrix();//读取之前的Matrix 77 } 78}