Lesson 110 +10 XP

Mesh API and Procedural Meshes

Mesh API and Procedural Meshes

Unity's Mesh API lets you generate and modify 3D mesh geometry programmatically at runtime.

Anatomy of a Mesh

A Mesh in Unity contains:

  • Vertices: Array of 3D points (Vector3[]).
  • Triangles: Array of integers grouped in threes. The order of indexes determines polygon face orientation (clockwise is front-facing).
  • UVs: Vector2 coordinates linking textures to coordinates (Vector2[]).
  • Normals: Vector3 direction vectors representing surface directions for lights.

Generating a Triangle Procedurally

using UnityEngine;

[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))]
public class ProceduralTriangle : MonoBehaviour
{
    void Start()
    {
        Mesh mesh = new Mesh();

        // 1. Define Vertices
        mesh.vertices = new Vector3[]
        {
            new Vector3(0, 0, 0),
            new Vector3(0, 1, 0),
            new Vector3(1, 0, 0)
        };

        // 2. Define Triangle (Clockwise winding order)
        mesh.triangles = new int[] { 0, 1, 2 };

        // 3. Define UV coordinates
        mesh.uv = new Vector2[]
        {
            new Vector2(0, 0),
            new Vector2(0, 1),
            new Vector2(1, 0)
        };

        // 4. Calculate Normals for lighting
        mesh.RecalculateNormals();

        GetComponent<MeshFilter>().mesh = mesh;
    }
}

High-Performance Modifying

If you are updating vertex offsets every frame, avoid creating garbage arrays:

  • Use Mesh.SetVertices(List<Vector3>) or write using the new Job-friendly Mesh.MeshDataArray system.
  • Always call RecalculateNormals() after changing vertex coordinates.

TL;DR

  • Create a Mesh instance, assign vertices, triangles, and UV arrays, then set to a MeshFilter.
  • Triangle vertex indexes must follow clockwise winding to be visible.
  • Always run RecalculateNormals() to update lighting directions.