Skip to main content
1 of 2

How to correctly draw a 2D polygon in Unity

I'm trying to draw a 2D polygon using GL.Line; however I'm not getting a polygon but separated lines instead. In the example below, I would expect a rectangle formed by the spheres:

enter image description here

My code is the following:

void OnPostRender( )
 {
     GL.PushMatrix ( );
     mat.SetPass ( 0 );
     GL.LoadOrtho( );

     GL.Begin( GL.LINES );
     GL.Color( Color.white );

     for ( int i = 0; i < spheres.Length; i++ )
     {
         currentVector = Camera.main.WorldToViewportPoint ( spheres[i].transform.position );
         GL.Vertex3 ( currentVector.x, currentVector.y , 0  );
     }

     GL.End();
     GL.PopMatrix();
 }

Also, I found this tutorial/example but is not exactly what i'm looking for, since in the example, all have the same origin point.

I'm asumming that the correct way of achieving what I want, would be to call the Gl.Vertex3 method once for each of the 2 points that form each line:

  • From A to B (GL.Vertex3 call 2 times)
  • From B to C (GL.Vertex3 call 2 times)
  • From C to D (GL.Vertex3 call 2 times)
  • From D to A (GL.Vertex3 call 2 times)

Is this the right way of doing this?

Thanks in advance.