# 5. Colliders Chunks and Level Design Part of [[Runtime Mesh Generation]]. Previous: [[4. Burst Jobs that Write Mesh Buffers]]. Next: [[6. Mesh Generation Tests Performance and Pitfalls]]. > [!warning] Code not compiled in Unity > Type-checked against 6000.5.8f1. Physics baking wasn't run. ## 5.1 Colliders for generated meshes Assigning `meshCollider.sharedMesh = mesh` makes PhysX **cook** the mesh, building its acceleration structure on the main thread. For a 65k-vertex heightfield that's a visible hitch. You can cook ahead of time on a worker with `Physics.BakeMesh`. PhysX caches the result, and the later `sharedMesh` assignment is cheap. `HeightfieldMesh` (part 4) already does this: ```csharp _bakeHandle = new BakeColliderJob { MeshId = _mesh.GetEntityId(), Convex = false }.Schedule(); // ... later, when _bakeHandle.IsCompleted: meshCollider.sharedMesh = null; meshCollider.sharedMesh = _mesh; ``` > [!important] 6000.5 API change > Older tutorials and older Scripting Reference examples pass `mesh.GetInstanceID()` to `Physics.BakeMesh(int, bool)`. In 6000.5 **both** are marked obsolete-as-error, so the code doesn't compile (CS0619). Use `GetEntityId()` and the `BakeMesh(EntityId, bool)` overload. The compiler confirmed this against the 6000.5.8f1 assemblies. Steps: 1. On the `Heightfield` object, add a **MeshCollider** and leave its Mesh empty. 2. Drag it into `HeightfieldMesh`'s **Mesh Collider** field. 3. Drop a Rigidbody sphere above the hills. It should land and roll after the first bake finishes. Notes: - **Bake with the cooking options the collider will use.** `BakeMesh(id, convex)` uses the default cooking options. If you change `MeshCollider.cookingOptions` in the Inspector, the cached bake won't match and Unity cooks again on assignment. (This comes from the Scripting Reference; it wasn't tested.) - **`sharedMesh = null` first** forces the collider to notice the mesh changed even though it's the same object. - **Convex** colliders are capped at 255 polygons and can't fit terrain. Use them for small generated props that need a dynamic Rigidbody. - For gameplay that only needs "how high is the ground here", skip the collider. Sample the same noise function on the CPU at that `(x, z)`. It's exact, free, and works before the mesh exists. That's the same idea as [[5. Runtime Terrain Queries and Deformation]]. ## 5.2 Chunks One 65k-vertex mesh is fine. A world isn't one mesh. Split it into chunks (for example, 64 × 64 cells each) so you can: - cull off-screen chunks (each has its own bounds), - rebuild only the chunk that changed (a crater, a dug tunnel), - stream chunks in and out by distance (the next tutorial in the queue covers open-world streaming), - stay under 65,535 vertices per chunk, so 16-bit indices are enough. **Seams:** neighbouring chunks share their edge row of vertices. As long as each chunk samples the noise at **world** coordinates (chunk origin + local offset), edge heights match exactly. With the central-difference normals from part 4, edge normals match too, because both chunks sample the same four neighbours. If you used `RecalculateNormals()` instead, edge normals would differ (each chunk sees only its own triangles), and you'd see lighting seams. Building many chunks at once: allocate them together and apply them together. ```csharp // Assets/Scripts/Meshes/ChunkBatchBuilder.cs using System.Collections.Generic; using Unity.Jobs; using Unity.Mathematics; using UnityEngine; using UnityEngine.Rendering; /// <summary> /// Builds N heightfield chunks in one MeshDataArray: one vertex + index job per chunk, /// all scheduled together, one ApplyAndDisposeWritableMeshData call for the whole list. /// Chunk (cx, cz) samples noise at world coordinates so edges match. /// </summary> public static class ChunkBatchBuilder { public static void Build(List<Mesh> meshes, List<Vector2Int> coords, int cells, float cellSize, float height, float frequency, int octaves) { var count = meshes.Count; var dataArray = Mesh.AllocateWritableMeshData(count); var handles = new Unity.Collections.NativeArray<JobHandle>(count * 2, Unity.Collections.Allocator.Temp); var vertexCount = (cells + 1) * (cells + 1); var cellCount = cells * cells; var span = cells * cellSize; for (var i = 0; i < count; i++) { var data = dataArray[i]; data.SetVertexBufferParams(vertexCount, HeightfieldMesh.Layout); data.SetIndexBufferParams(cellCount * 6, IndexFormat.UInt32); var origin = new float2(coords[i].x * span, coords[i].y * span); handles[i * 2] = new HeightfieldVertexJob { CellsX = cells, CellsZ = cells, CellSize = cellSize, Height = height, Frequency = frequency, Octaves = octaves, Offset = origin, Vertices = data.GetVertexData<HeightfieldVertex>(0) }.Schedule(vertexCount, 256); handles[i * 2 + 1] = new HeightfieldIndexJob { CellsX = cells, Indices = data.GetIndexData<uint>() }.Schedule(cellCount, 256); } JobHandle.CombineDependencies(handles).Complete(); handles.Dispose(); var bounds = new Bounds(new Vector3(span * 0.5f, 0f, span * 0.5f), new Vector3(span, height * 2f, span)); for (var i = 0; i < count; i++) { var data = dataArray[i]; data.subMeshCount = 1; data.SetSubMesh(0, new SubMeshDescriptor(0, cellCount * 6) { bounds = bounds, vertexCount = vertexCount }, MeshUpdateFlags.DontRecalculateBounds); } Mesh.ApplyAndDisposeWritableMeshData(dataArray, meshes, MeshUpdateFlags.DontRecalculateBounds); for (var i = 0; i < count; i++) meshes[i].bounds = bounds; } } ``` Note how the chunk's vertices sit in **local** space (0…span) while the noise samples **world** space through `Offset = origin`. Position each chunk's GameObject at `(cx * span, 0, cz * span)`. This builder blocks with `Complete()` for simplicity. For a streaming world, keep the handle and the array, and apply on a later frame as in part 4. With 16-bit indices you could save memory here (65 × 65 = 4,225 vertices per chunk), but the shared index job writes `uint`, so this example keeps UInt32. ## 5.3 When to generate (and when not to) [[Level Up! (Review)]] is blunt that players experience **spaces with intent**: a landmark to steer by, a sightline that reveals the goal, a choke point that sets pace. Noise has no intent. Use generation for: - **Texture between authored beats:** hills between hand-placed villages. Generate the ground, author the landmarks, and flatten the noise under them with a mask. - **Player-made geometry:** drawn walls, painted paths, deformable snow. The player *is* the designer there. - **Infinite or replayable runs:** where variety is the point. Pair with the beat-chart constraints from [[4. Design Constraints and Beat Charts]]. Don't generate what a level designer should place. [[ProBuilder Gray-Boxing and Landmarks]] and [[Terrain]] are faster tools for authored spaces. A common hybrid: generate the base mesh, then let designers paint a **height mask texture** that the vertex job samples (read it into a `NativeArray<float>` once) to flatten arenas and carve paths.