Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Last active May 19, 2023 06:17
Show Gist options
  • Save unitycoder/a3f3579eec052e223023 to your computer and use it in GitHub Desktop.
Save unitycoder/a3f3579eec052e223023 to your computer and use it in GitHub Desktop.
DrawLine with GL
using UnityEngine;
public class DrawLine : MonoBehaviour
{
Color lineColor = Color.red;
float distance = 100;
Material lineMaterial;
void CreateLineMaterial()
{
if (!lineMaterial)
{
// Unity has a built-in shader that is useful for drawing
// simple colored things.
var shader = Shader.Find("Hidden/Internal-Colored");
lineMaterial = new Material(shader);
lineMaterial.hideFlags = HideFlags.HideAndDontSave;
// Turn on alpha blending
lineMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
lineMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
// Turn backface culling off
lineMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off);
// Turn off depth writes
lineMaterial.SetInt("_ZWrite", 0);
}
}
// cannot call this on update, line not visible then.. and OnPostRender() works on camera only
void OnRenderObject()
{
CreateLineMaterial();
lineMaterial.SetPass(0);
GL.PushMatrix();
GL.MultMatrix(transform.localToWorldMatrix); // not needed if already in worldspace
GL.Begin(GL.LINES);
GL.Color(lineColor);
GL.Vertex3(transform.position.x, transform.position.y, transform.position.z);
GL.Vertex3(transform.position.x + transform.forward.x * distance, transform.position.y + transform.forward.y * distance, transform.position.z + transform.forward.z * distance);
GL.End();
GL.PopMatrix();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment