# 3. The MeshData API and Vertex Layouts Part of [[Runtime Mesh Generation]]. Previous: [[2. A Procedural Grid with the Simple API]]. Next: [[4. Burst Jobs that Write Mesh Buffers]]. > [!warning] Code not compiled in Unity > Type-checked against 6000.5.8f1's `UnityEngine.CoreModule` and `Unity.Collections`. Not run in a scene. The simple API owns the data layout for you. Each attribute (positions, normals, UVs) is a separate array, and every `Set*` call copies and converts. The **MeshData API** hands *you* the vertex buffer as a `NativeArray<T>` of *your* struct. You write into it, then give it to the mesh in one step. ## 3.1 The five calls ```text Mesh.AllocateWritableMeshData(n) -> MeshDataArray (n writable MeshData) data.SetVertexBufferParams(count, layout) -> sizes the vertex buffer, declares attributes data.SetIndexBufferParams(count, format) -> sizes the index buffer (UInt16 or UInt32) data.GetVertexData<T>(stream) / GetIndexData<T>() -> NativeArray views you write into data.subMeshCount = k; data.SetSubMesh(i, descriptor, flags) Mesh.ApplyAndDisposeWritableMeshData(array, mesh, flags) -> moves the data in and frees the array ``` You must call `ApplyAndDisposeWritableMeshData` **or** `Dispose()` on the array exactly once. If you forget, you leak native memory, and in the Editor the leak detector complains about an undisposed allocation. ## 3.2 Vertex layout is a contract ```csharp [StructLayout(LayoutKind.Sequential)] public struct Vertex { public Vector3 Position; public Vector3 Normal; public Vector2 Uv; } // 32 bytes new VertexAttributeDescriptor(VertexAttribute.Position, VertexAttributeFormat.Float32, 3), new VertexAttributeDescriptor(VertexAttribute.Normal, VertexAttributeFormat.Float32, 3), new VertexAttributeDescriptor(VertexAttribute.TexCoord0, VertexAttributeFormat.Float32, 2), ``` Three rules: 1. **Attributes must be listed in Unity's fixed order:** Position, Normal, Tangent, Color, TexCoord0–7, BlendWeight, BlendIndices. You can skip attributes, but you can't reorder them. 2. **The struct's field order and sizes must match the descriptor list** for that stream byte for byte. Unity doesn't check your struct. A mismatch renders as exploded spikes. 3. **Dimensions must be multiples of 4 bytes.** For example, `Float16 × 2` (4 bytes) is OK and `Float16 × 3` (6 bytes) is not. That's how you halve UV memory: `TexCoord0, Float16, 2` with a `half2` field. All attributes above are on **stream 0** (interleaved). You can put an attribute on another stream (`new VertexAttributeDescriptor(..., stream: 1)`) when one part changes every frame and the rest doesn't. For example, rewrite positions on stream 0 and keep UVs untouched on stream 1. ## 3.3 WritableMeshGrid Same grid as part 2, on the main thread, with the MeshData API: ```csharp // Assets/Scripts/Meshes/WritableMeshGrid.cs using System.Runtime.InteropServices; using Unity.Collections; using UnityEngine; using UnityEngine.Rendering; /// <summary> /// Same grid, built with the advanced MeshData API: one interleaved vertex stream /// (position, normal, uv0), explicit index format, one SubMeshDescriptor, then /// Mesh.ApplyAndDisposeWritableMeshData. Main thread only; see HeightfieldMeshJob for the jobified version. /// </summary> [RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))] public sealed class WritableMeshGrid : MonoBehaviour { [StructLayout(LayoutKind.Sequential)] public struct Vertex { public Vector3 Position; public Vector3 Normal; public Vector2 Uv; } public static readonly VertexAttributeDescriptor[] Layout = { new VertexAttributeDescriptor(VertexAttribute.Position, VertexAttributeFormat.Float32, 3), new VertexAttributeDescriptor(VertexAttribute.Normal, VertexAttributeFormat.Float32, 3), new VertexAttributeDescriptor(VertexAttribute.TexCoord0, VertexAttributeFormat.Float32, 2), }; [SerializeField, Min(1)] int cellsX = 128; [SerializeField, Min(1)] int cellsZ = 128; [SerializeField, Min(0.01f)] float cellSize = 0.25f; Mesh _mesh; void OnEnable() { _mesh = new Mesh { name = "WritableMeshGrid (runtime)" }; GetComponent<MeshFilter>().sharedMesh = _mesh; Build(); } void OnDisable() { if (_mesh != null) Destroy(_mesh); _mesh = null; } [ContextMenu("Build")] public void Build() { var vertexCount = GridTopology.VertexCount(cellsX, cellsZ); var indexCount = GridTopology.IndexCount(cellsX, cellsZ); var use32 = GridTopology.Needs32BitIndices(cellsX, cellsZ); var dataArray = Mesh.AllocateWritableMeshData(1); var data = dataArray[0]; data.SetVertexBufferParams(vertexCount, Layout); data.SetIndexBufferParams(indexCount, use32 ? IndexFormat.UInt32 : IndexFormat.UInt16); var vertices = data.GetVertexData<Vertex>(0); for (var z = 0; z <= cellsZ; z++) for (var x = 0; x <= cellsX; x++) { vertices[GridTopology.VertexIndex(x, z, cellsX)] = new Vertex { Position = new Vector3(x * cellSize, 0f, z * cellSize), Normal = Vector3.up, Uv = new Vector2((float)x / cellsX, (float)z / cellsZ) }; } var cell = new int[6]; if (use32) { var indices = data.GetIndexData<uint>(); WriteIndices(indices, cell); } else { var indices = data.GetIndexData<ushort>(); WriteIndices(indices, cell); } var bounds = new Bounds( new Vector3(cellsX * cellSize * 0.5f, 0f, cellsZ * cellSize * 0.5f), new Vector3(cellsX * cellSize, 0.01f, cellsZ * cellSize)); data.subMeshCount = 1; data.SetSubMesh(0, new SubMeshDescriptor(0, indexCount, MeshTopology.Triangles) { bounds = bounds, vertexCount = vertexCount }, MeshUpdateFlags.DontRecalculateBounds); Mesh.ApplyAndDisposeWritableMeshData(dataArray, _mesh, MeshUpdateFlags.DontRecalculateBounds); _mesh.bounds = bounds; } void WriteIndices(NativeArray<uint> indices, int[] cell) { var o = 0; for (var z = 0; z < cellsZ; z++) for (var x = 0; x < cellsX; x++) { GridTopology.WriteCell(x, z, cellsX, cell, 0); for (var k = 0; k < 6; k++) indices[o++] = (uint)cell[k]; } } void WriteIndices(NativeArray<ushort> indices, int[] cell) { var o = 0; for (var z = 0; z < cellsZ; z++) for (var x = 0; x < cellsX; x++) { GridTopology.WriteCell(x, z, cellsX, cell, 0); for (var k = 0; k < 6; k++) indices[o++] = (ushort)cell[k]; } } } ``` ### Walkthrough 1. `AllocateWritableMeshData(1)` gives one writable `MeshData`. Ask for *n* when you build *n* chunks at once. There's an overload of `ApplyAndDisposeWritableMeshData` that takes a `List<Mesh>`. 2. `SetVertexBufferParams` sizes the buffer and fixes the layout. `GetVertexData<Vertex>(0)` reinterprets stream 0 as your struct. **The array isn't zeroed**, so write every element. 3. `SetIndexBufferParams(indexCount, UInt16 or UInt32)`, then `GetIndexData<ushort>()` or `GetIndexData<uint>()`. The generic type **must** match the format. That's why there are two `WriteIndices` overloads. 4. `SetSubMesh` with a `SubMeshDescriptor(indexStart, indexCount, topology)`. Passing `MeshUpdateFlags.DontRecalculateBounds` and filling `bounds` and `vertexCount` yourself skips a pass over every vertex. You know the bounds of a grid analytically. 5. `ApplyAndDisposeWritableMeshData(..., DontRecalculateBounds)` swaps the buffers into the mesh. Then set `mesh.bounds` to the same box. ### Useful flags | `MeshUpdateFlags` | Skips | Use when | |---|---|---| | `DontValidateIndices` | the check that each index is < vertexCount | your index math is tested (part 6) | | `DontRecalculateBounds` | the bounds pass | you set bounds yourself | | `DontResetBoneBounds` | skinned-mesh bone bounds reset | non-skinned meshes | | `DontNotifyMeshUsers` | renderer/collider "mesh changed" callbacks | you'll update colliders yourself | Only skip validation once the tests pass. An out-of-range index with validation off can crash the GPU driver on some platforms. ## 3.4 Reading meshes without garbage `mesh.vertices` returns a **new** `Vector3[]` on every access. In a loop, that's an allocation per call. `Mesh.AcquireReadOnlyMeshData` gives you `NativeArray` views instead. It also works inside jobs. Imported meshes need **Read/Write** enabled in their import settings for CPU access in a Player build; meshes you create at runtime are readable by default. (That Read/Write rule comes from the Mesh import docs and wasn't tested here.) ```csharp // Assets/Scripts/Meshes/MeshReadback.cs using Unity.Collections; using UnityEngine; /// <summary> /// Reads vertex positions from any readable Mesh with Mesh.AcquireReadOnlyMeshData, /// which avoids the managed Vector3[] copy that mesh.vertices makes. Dispose the array. /// </summary> public static class MeshReadback { public static float HighestPoint(Mesh mesh) { using (var dataArray = Mesh.AcquireReadOnlyMeshData(mesh)) { var data = dataArray[0]; using (var positions = new NativeArray<Vector3>(data.vertexCount, Allocator.Temp)) { data.GetVertices(positions); var max = float.NegativeInfinity; for (var i = 0; i < positions.Length; i++) max = Mathf.Max(max, positions[i].y); return max; } } } } ``` Use it for gameplay queries such as "highest point on this generated island", "spawn on a random triangle", or "vertex colours as a fog-of-war mask". The `using` blocks guarantee both native allocations are disposed, even if something throws. ## 3.5 Exercise Change the layout to put UVs at half precision: 1. Add `using Unity.Mathematics;` and make the field `public half2 Uv;`. 2. Change the descriptor to `VertexAttributeFormat.Float16, 2`. 3. Write `Uv = new half2(new half(u), new half(v))`. The vertex shrinks from 32 to 28 bytes. (This exercise variant wasn't compiled.) On a 65k-vertex chunk that's 256 KB saved. Check it in the Memory Profiler.