Polygon Generation in Unity

Dynamic generation of polygonal 2d meshes is a useful stepping stone to more dynamic shapes. Unity Mesh object can be broken down into two major components, an array of Vector3s and an array of integers. The simplest polygons have equal angles and side lengths, this is an easy calculation to do; to calculate the X and Y values we use Cosine and Sine functions.

float angle = Mathf.Deg2Rad * ( 360 / sides );
Vector3[] verts = new Vector3[sides];
for (int i = 0; i < verts.Length; i++)
{
    float h = angle * i;
    float x = Mathf.Cos(h) * distance;
    float y = Mathf.Sin(h) * distance;
    verts[i] = new Vector3(x, y, 0.0f);
 }

The next step of making a mesh dynamically is to determine the triangles that the face is made up of. We first figure out how many triangles we require, this can be done by taking the number of vertices and subtract 2. Now we can walk thru each triangle and determine the index of each vertex. Making the simple assumption that every triangle of the face is going to start at the first vertex; we then have to determine the two other vertices. Once we determine the vertex indices of the individual triangles we then have to add them to the mesh triangles indices list. Before we can add them to that array we must order them so that the faces are facing the correct direction.

List<int> triangles = new List<int>();
int triangleCount = verts.Length - 2;
for (int i = 0; i < triangleCount; i++)
{
    int a = 0;
    int b = 1 + i;
    int c = 2 + i;
    switch (faceDirection)
    {
        case FaceDirection.FRONT:
            triangles.AddRange(new int[] { c, b, a });
            break;
        case FaceDirection.BACK:
            triangles.AddRange(new int[] { a, b, c });
            break;
        case FaceDirection.BOTH:
            triangles.AddRange(new int[] { c, b, a });
            triangles.AddRange(new int[] { a, b, c });
            break;
    }
}

Now that we have both the components we need, time to apply them to the mesh object.

Mesh mesh = new Mesh();
mesh.vertices = verts;
mesh.triangles = triangles.ToArray();

Once you have the mesh object, you will have to set it to the MeshFilter component on a game object. This can be used in both the Start and Update methods.