# 1. Mesh Anatomy and the Simple API Part of [[Runtime Mesh Generation]]. Next: [[2. A Procedural Grid with the Simple API]]. > [!warning] Code not compiled in Unity > Type-checked against the 6000.5.8f1 Editor assemblies (see the hub). Not run in a scene. ## 1.1 What a Mesh actually is A `Mesh` is two buffers plus some bookkeeping: - **Vertex buffer**: one entry per vertex. Each entry has **attributes**: `Position` (always), and optionally `Normal`, `Tangent`, `Color`, `TexCoord0..7`, `BlendWeight`/`BlendIndices` for skinning. - **Index buffer**: a list of integers. With `MeshTopology.Triangles`, every three indices make one triangle that points back into the vertex buffer. - **Submeshes**: ranges of the index buffer. Submesh *i* is drawn with `MeshRenderer.sharedMaterials[i]`. - **Bounds**: an axis-aligned box used for frustum culling. If it's wrong, the mesh pops out of view at the screen edge. The important rule: **a vertex is the whole bundle of attributes.** A cube corner where three faces meet with three different normals (flat shading) is **three vertices**, not one. That's why a Unity cube has 24 vertices, not 8. | Shared vertices | Split vertices | |---|---| | Fewer vertices, smooth shading (normals averaged) | Hard edges, a separate UV per face | | Terrain, cloth, blobs | Boxes, low-poly flat-shaded art, UV seams | ## 1.2 Winding order Unity draws a triangle's **front face** when its three vertices appear **clockwise** on screen. Counter-clockwise triangles are back faces, and the default (`Cull Back`) hides them. For a quad seen from the front, with corners bottom-left, top-left, top-right, bottom-right: ```text tl ---- tr | / | triangle 1: bl, tl, tr (clockwise) | / | triangle 2: bl, tr, br (clockwise) bl ---- br ``` If your generated mesh is invisible but its outline shows when selected, the winding is backwards. Swap two indices in every triangle. Don't fix it by switching the material to double-sided: that doubles fragment work and breaks lighting on the back. ## 1.3 Index format: 16-bit versus 32-bit `Mesh.indexFormat` defaults to `IndexFormat.UInt16`, which can address **65,535** vertices. Go past that and you need `IndexFormat.UInt32`. **Set it before you assign triangles.** UInt32 doubles index memory and isn't supported on every old mobile GPU, so only use it when you have to. Part 2's `GridTopology.Needs32BitIndices` makes the decision explicit. ## 1.4 Normals, tangents and bounds - `mesh.RecalculateNormals()` averages face normals over **shared** vertices. It's fine for most procedural shapes. It costs main-thread time, so on large meshes part 4 computes normals in the job instead. - `mesh.RecalculateTangents()` is needed only if the material uses a **normal map**. - `mesh.RecalculateBounds()` runs automatically when you call `SetTriangles(..., calculateBounds: true)`. If you skip it, set `mesh.bounds` yourself. ## 1.5 MeshBuilder: the simple API, reusably Every procedural shape ends up as "append vertices, append triangles, upload". Here's that pattern once, backed by lists you reuse between rebuilds so you don't allocate on every rebuild. ```csharp // Assets/Scripts/Meshes/MeshBuilder.cs using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; /// <summary> /// A tiny list-backed builder for the "simple" Mesh API: AddQuad / AddTriangle, /// then ApplyTo(mesh). Reuse one builder (Clear) to avoid per-rebuild garbage. /// </summary> public sealed class MeshBuilder { readonly List<Vector3> _positions = new List<Vector3>(256); readonly List<Vector3> _normals = new List<Vector3>(256); readonly List<Vector2> _uvs = new List<Vector2>(256); readonly List<int> _indices = new List<int>(384); public int VertexCount => _positions.Count; public void Clear() { _positions.Clear(); _normals.Clear(); _uvs.Clear(); _indices.Clear(); } public int AddVertex(Vector3 position, Vector3 normal, Vector2 uv) { _positions.Add(position); _normals.Add(normal); _uvs.Add(uv); return _positions.Count - 1; } /// <summary>Clockwise a, b, c (as seen from the front) is front-facing in Unity.</summary> public void AddTriangle(int a, int b, int c) { _indices.Add(a); _indices.Add(b); _indices.Add(c); } /// <summary> /// Adds a flat quad. Corners in clockwise order as seen from the front: /// bottom-left, top-left, top-right, bottom-right. /// </summary> public void AddQuad(Vector3 bl, Vector3 tl, Vector3 tr, Vector3 br) { var normal = Vector3.Cross(tl - bl, br - bl).normalized; var i0 = AddVertex(bl, normal, new Vector2(0f, 0f)); var i1 = AddVertex(tl, normal, new Vector2(0f, 1f)); var i2 = AddVertex(tr, normal, new Vector2(1f, 1f)); var i3 = AddVertex(br, normal, new Vector2(1f, 0f)); AddTriangle(i0, i1, i2); AddTriangle(i0, i2, i3); } public void ApplyTo(Mesh mesh) { mesh.Clear(); mesh.indexFormat = _positions.Count > 65535 ? IndexFormat.UInt32 : IndexFormat.UInt16; mesh.SetVertices(_positions); mesh.SetNormals(_normals); mesh.SetUVs(0, _uvs); mesh.SetTriangles(_indices, 0, true); } } ``` What to notice: - `mesh.Clear()` comes **first**. If you shrink the vertex count while old triangles still point past the end, `SetVertices` throws (or logs) an out-of-range index error. - The overloads `SetVertices(List<Vector3>)`, `SetNormals`, `SetUVs(int channel, List<Vector2>)` and `SetTriangles(List<int>, int submesh, bool calculateBounds)` take **lists**, not arrays. Unlike the old `mesh.vertices = array` property, they don't make an extra copy. - `AddQuad` computes the face normal with `Vector3.Cross(tl - bl, br - bl)`. For clockwise corners that cross product points out of the front face (Unity's left-handed coordinates). ## 1.6 Try it: a flat-shaded box 1. Create an empty GameObject called `GeneratedBox`. Add a **MeshFilter** and a **MeshRenderer** with any Lit material. 2. Add this script: ```csharp // Assets/Scripts/Meshes/GeneratedBox.cs using UnityEngine; [RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))] public sealed class GeneratedBox : MonoBehaviour { [SerializeField] Vector3 size = new Vector3(1f, 1f, 1f); readonly MeshBuilder _builder = new MeshBuilder(); Mesh _mesh; void OnEnable() { _mesh = new Mesh { name = "GeneratedBox" }; GetComponent<MeshFilter>().sharedMesh = _mesh; Build(); } void OnDisable() { if (_mesh != null) Destroy(_mesh); } [ContextMenu("Build")] void Build() { var h = size * 0.5f; var p000 = new Vector3(-h.x, -h.y, -h.z); var p100 = new Vector3(h.x, -h.y, -h.z); var p010 = new Vector3(-h.x, h.y, -h.z); var p110 = new Vector3(h.x, h.y, -h.z); var p001 = new Vector3(-h.x, -h.y, h.z); var p101 = new Vector3(h.x, -h.y, h.z); var p011 = new Vector3(-h.x, h.y, h.z); var p111 = new Vector3(h.x, h.y, h.z); _builder.Clear(); _builder.AddQuad(p000, p010, p110, p100); // front (-Z) _builder.AddQuad(p101, p111, p011, p001); // back (+Z) _builder.AddQuad(p001, p011, p010, p000); // left (-X) _builder.AddQuad(p100, p110, p111, p101); // right (+X) _builder.AddQuad(p010, p011, p111, p110); // top (+Y) _builder.AddQuad(p001, p000, p100, p101); // bottom (-Y) _builder.ApplyTo(_mesh); } } ``` 3. Press Play. You should see a box with hard edges: 24 vertices, 12 triangles. Open **Frame Debugger** or the Inspector's mesh preview to confirm the counts. 4. Break it on purpose: swap the `tl` and `br` arguments in the `top` line. The top face disappears from above and appears from inside. That's what wrong winding looks like. > [!tip] Destroy what you `new` > A `new Mesh()` is a native asset. It is **not** garbage-collected with the component that made it. Every generator in this series destroys its mesh in `OnDisable`. Without that, entering and leaving Play Mode (or toggling the object) leaks meshes. You'll see them pile up in the Memory Profiler. ## 1.7 Pattern note `MeshBuilder` is a small *Builder*: it accumulates parts and produces the product (`ApplyTo`) at the end. Reusing its lists is the same allocation discipline as [[Object Pooling and Spawners]], applied to buffers instead of GameObjects. See [[Game Programming Patterns (Review)]] for why "allocate once, reuse forever" matters more in games than in most software.