新建一个脚本,这个物体得挂在有摄像机组件的物体上才能生效
OnPostRender() 这个函数才会被自动调用(类似生命周期自动调用)
然后就可以代码画线了,原理是openGL的画线
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// GL画图
/// </summary>
public class GLDraw : UnityNormalSingleton<GLDraw> {
public Transform p1;
public Transform p2;
private List<Vector2> pointList;
private bool isOpen;
private Material mat;
private Shader shader;
private void Start()
{
pointList = new List<Vector2>();
shader = Shader.Find("Unlit/Color");
mat = new Material(shader);
mat.SetColor("Main Color", Color.black);
}
public void DrawLine(List<object> list)
{
pointList.Clear();
for (int i = 0; i < list.Count; i++)
{
Vector2 screenPos = (Vector2)list[i];
pointList.Add(new Vector2(screenPos.x, Screen.height - screenPos.y));
}
}
public void ShowLine(bool b)
{
isOpen = b;
}
void OnPostRender()
{
if (!isOpen)
{
return;
}
//mat = new Material(Shader.Find("Unlit/Color"));
//Debug.Log("调用");
//if (!mat)
//{
// Debug.LogError("Please Assign a material on the inspector");
// return;
//}
GL.PushMatrix(); //保存当前Matirx
mat.SetPass(0); //刷新当前材质
GL.LoadPixelMatrix();//设置pixelMatrix
GL.Color(Color.yellow);
GL.Begin(GL.LINES);
//画2次,奇偶数画连续折线法
for (int i = 0; i < pointList.Count; i++)
{
GL.Vertex3(pointList[i].x, pointList[i].y, 0);
}
for (int i = 1; i < pointList.Count; i++)
{
GL.Vertex3(pointList[i].x, pointList[i].y, 0);
}
//单次画线发
//GL.Vertex3(0, 0, 0);//GL.Vertex3(Screen.width, Screen.height, 0);
//固定2点画
//GL.Vertex3(p1.position.x, p1.position.y, 0);
//GL.Vertex3(p2.position.x, p2.position.y, 0);
GL.End();
GL.PopMatrix();//读取之前的Matrix
}
}