# 6. Mesh Generation Tests Performance and Pitfalls
Part of [[Runtime Mesh Generation]]. Previous: [[5. Colliders Chunks and Level Design]].
> [!warning] Test status
> The assertions below ran against `GridTopology` as a .NET 10 console program on 2026-12-01: **7/7 passed**. The NUnit version for the Unity Test Framework was type-checked only; it wasn't run in the Test Runner.
## 6.1 What to test
Mesh bugs show up as visuals ("half my terrain is spikes"), so it's tempting to debug by eye. Test the **topology math** instead. It's pure, and a single off-by-one in it explains most of those visuals.
```csharp
// Assets/Tests/EditMode/GridTopologyTests.cs (asmdef: Editor only, references the runtime asmdef + nunit)
using NUnit.Framework;
public class GridTopologyTests
{
[Test]
public void OneCellHasFourVerticesAndSixIndices()
{
Assert.AreEqual(4, GridTopology.VertexCount(1, 1));
Assert.AreEqual(6, GridTopology.IndexCount(1, 1));
}
[Test]
public void Grid255Needs32BitIndices()
{
Assert.AreEqual(65536, GridTopology.VertexCount(255, 255));
Assert.IsTrue(GridTopology.Needs32BitIndices(255, 255));
Assert.IsFalse(GridTopology.Needs32BitIndices(254, 255)); // 65,280 vertices
}
[Test]
public void CellWindingIsClockwiseFromAbove()
{
var idx = GridTopology.BuildIndices(1, 1);
CollectionAssert.AreEqual(new[] { 0, 2, 3, 0, 3, 1 }, idx);
// Vertex i of a 1-cell-wide grid is at (i % 2, 0, i / 2).
float ax = idx[0] % 2, az = idx[0] / 2;
float bx = idx[1] % 2, bz = idx[1] / 2;
float cx = idx[2] % 2, cz = idx[2] / 2;
// y component of (b - a) x (c - a); positive means the face normal points +Y.
var crossY = (bz - az) * (cx - ax) - (bx - ax) * (cz - az);
Assert.Greater(crossY, 0f);
}
[Test]
public void EveryVertexIsReferenced()
{
var idx = GridTopology.BuildIndices(10, 7);
Assert.AreEqual(420, idx.Length);
var max = 0;
foreach (var i in idx)
max = System.Math.Max(max, i);
Assert.AreEqual(GridTopology.VertexCount(10, 7) - 1, max);
}
[Test]
public void ZeroCellsThrows()
{
Assert.Throws<System.ArgumentOutOfRangeException>(() => GridTopology.VertexCount(0, 3));
}
}
```
The console run that actually executed was the same assertions with `Console.WriteLine` output:
```text
PASS 1x1 grid has 4 vertices and 6 indices
PASS 256x256 vertices needs 32-bit indices
PASS 255x256 = 65280 vertices fits 16-bit
PASS 1x1 winding bl,tl,tr / bl,tr,br
PASS triangle normal (u x v) points +Y, so visible from above in Unity
PASS 10x7 indices reference every vertex up to the last
PASS zero cells throws
ALL PASS
```
A **PlayMode** test worth adding (not written here): build `WritableMeshGrid` with `cellsX = cellsZ = 4`, then assert `mesh.vertexCount == 25`, `mesh.GetIndexCount(0) == 96` and `mesh.bounds.size.x == 4 * cellSize`. See [[Unity Test Framework]] for the asmdef setup.
## 6.2 Measuring
Wrap your own sections in `ProfilerMarker`s (`Unity.Profiling`) so they show up by name:
```csharp
// Assets/Scripts/Meshes/MeshMarkers.cs
using Unity.Profiling;
public static class MeshMarkers
{
public static readonly ProfilerMarker Schedule = new ProfilerMarker("Mesh.ScheduleBuild");
public static readonly ProfilerMarker Apply = new ProfilerMarker("Mesh.ApplyBuild");
}
// usage: using (MeshMarkers.Apply.Auto()) { Mesh.ApplyAndDisposeWritableMeshData(...); }
```
Then compare in the **Profiler (Timeline)**, on a development build, on the target device:
| Variant (65k vertices) | Watch |
|---|---|
| Simple API + `RecalculateNormals` (part 2) | main-thread `Mesh.SetVertices`, `RecalculateNormals`, GC Alloc column |
| MeshData on the main thread (part 3) | main-thread loop time, 0 B GC |
| Burst jobs (part 4) | worker lanes busy, main thread mostly `ApplyAndDispose` |
| + MeshCollider assignment without bake | `MeshCollider.sharedMesh` spike |
| + `BakeMesh` job (part 5) | spike moves to a worker |
This note gives no numbers on purpose, because none were measured. Measure yours ([[Profiling and Optimization]]).
## 6.3 Quest and mobile budgets
- **Vertex count is rarely the limit; overdraw and draw calls are.** A 65k-vertex chunk is one draw call. Twenty small chunks are twenty. Merge where culling doesn't help.
- **Use 16-bit indices** where you can (chunks ≤ 254 × 254 cells). UInt32 doubles index bandwidth.
- **Halve UVs** (`Float16 × 2`) and pack colours (`UNorm8 × 4`). Mobile GPUs are bandwidth-bound.
- **Don't rebuild every frame on Quest** unless you must. Rebuild on change (*Dirty Flag*) and spread chunk rebuilds over frames, one or two per frame. The heightfield's `IsCompleted` check already avoids stalls.
- **Mind Burst's target.** Burst compiles ahead of time for Android ARM64 in the Player build. Check **Project Settings → Burst AOT Settings** for Android if a job runs much slower on device than in the Editor.
- Tie the cell density to a quality tier from [[Scalability and Quality Tiers]] (for example, 128 cells on Quest, 255 on PC).
## 6.4 Pitfalls checklist
| Symptom | Cause | Fix |
|---|---|---|
| Mesh invisible from the expected side | Counter-clockwise winding | Swap two indices per triangle (part 1) |
| Half the mesh is spikes or missing | > 65,535 vertices with UInt16 indices | Set `indexFormat = UInt32` **before** `SetTriangles`, or split into chunks |
| "Mesh.vertices is too small" / index out of range | Shrinking vertices while old triangles exist | `mesh.Clear()` first |
| Exploded, stretched triangles with MeshData | Struct layout doesn't match the descriptors, or attributes out of Unity's order | Match fields 1:1, keep Position → Normal → … → TexCoord order (part 3) |
| Mesh vanishes at screen edges | Stale or zero bounds | `RecalculateBounds()` or set `bounds` (+ `SubMeshDescriptor.bounds`) |
| Lighting seams between chunks | `RecalculateNormals()` per chunk | Analytic or central-difference normals at world coordinates (part 4) |
| Native leak warnings | `MeshDataArray` never applied or disposed; `AcquireReadOnlyMeshData` not disposed | `ApplyAndDispose…` or `Dispose` exactly once; `using` for read-only |
| Crash or exception on disable | Disposing while a job still writes | `Complete()` before `Dispose()` (part 4 `OnDisable`) |
| Meshes pile up in the Memory Profiler | `new Mesh()` never destroyed | `Destroy(mesh)` in `OnDisable`/`OnDestroy` |
| CS0619 on `GetInstanceID` / `BakeMesh(int, bool)` | 6000.5 EntityId migration | `GetEntityId()` and `BakeMesh(EntityId, bool)` (part 5) |
| Hitch when a collider updates | PhysX cooking on the main thread | `Physics.BakeMesh` in a job first (part 5) |
| Normal maps look wrong | No tangents | `RecalculateTangents()` or write tangents in the job |
## 6.5 Where to go next
- Chunk streaming by distance: the *Open-World Streaming* tutorial, next in the queue.
- GPU-side generation (compute shader writes a `GraphicsBuffer` used as a vertex buffer): [[Compute Shaders and GPU Instancing]].
- Data-oriented thinking behind all of this: *Data Locality* and *Dirty Flag* in [[Game Programming Patterns (Review)]].