# How do I combine meshes in code?

So let’s say I have six separate sides that I created that represents a cube. But I’ll need to mash all six side meshes into one mesh that would represent a cube. And to be even more efficient, I need to take all cube meshes within a 16x16x256 area and combine them into a chunk mesh, which will then be attached to a GameObject. So I know how to create all the different sides (right, left, top, bottom, front, back) but I just can’t figure out to combine the meshes together. I also need to have multiple materials for the same mesh if that is possible. The code below demonstrates how I go about creating a side.

``````public Mesh CreateSide(Vector3[] vertices, int[] triangles){
Mesh mesh = new Mesh ();
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = standardMeshUV;
MeshUtility.Optimize (mesh);
mesh.RecalculateNormals ();
return mesh;
}
public Mesh CreateFrontSide(){
Vector3[] vertices = new Vector3[] {
new Vector3 (-1, 1, 1),
new Vector3 (1, 1, 1),
new Vector3 (-1, -1, 1),
new Vector3 (1, -1, 1)
};
int[] triangles = new int[] {
0, 2, 3,
3, 1, 0,
};
return CreateSide (meshFilter, vertices, triangles);
}
``````

Apparently, the simplest option is to just store all the meshes in GameObjects, combine them using mesh.CombineMeshes, and then delete all the GameObjects that were created. I’m sure there is a better option in terms of taking up fewer resources, but it seems to work alright.

``````	public GameObject CreateChunk(short chunkX, short chunkY){

List<GameObject> physicalBlocks = new List<GameObject> ();

for (short y = 0; y < height; y++) {
for (short x = (short)(chunkX * chunkSize); x < (short)(chunkX * chunkSize) + chunkSize; x++) {
for (short z = (short)(chunkY * chunkSize); z < (short)(chunkY * chunkSize) + chunkSize; z++) {
GameObject physicalBlock = CreatePhysicalBlock (blocks [x, y, z]);
if (physicalBlock != null) {
physicalBlock.name = x + "," + y + "," + z;
}
}
}
}
//Merge physical blocks into one chunk.
CombineInstance[] combine = new CombineInstance[physicalBlocks.Count];

for(int i = 0; i < physicalBlocks.Count; i++){
combine_.mesh = physicalBlocks*.GetComponent<MeshFilter> ().sharedMesh;*_
``````

combine_.transform = physicalBlocks*.transform.localToWorldMatrix;
}*_

* GameObject chunk = new GameObject ();*
* chunk.transform.GetComponent ().mesh = new Mesh ();*
* chunk.transform.GetComponent ().mesh.CombineMeshes (combine, true);*
* chunk.GetComponent ().sharedMesh = chunk.GetComponent ().sharedMesh;*
* chunk.GetComponent().material = atlasMaterial;*
* chunk.transform.GetComponent ().mesh.RecalculateBounds ();*
* chunk.transform.GetComponent ().mesh.RecalculateNormals ();*
* MeshUtility.Optimize (chunk.GetComponent ().mesh);*

* for (int i = physicalBlocks.Count; i > 0; i–) {*
* Destroy (physicalBlocks[i - 1]);*
* }*

* chunk.name = “Chunk_” + chunkX + "" + chunkY;*
* return chunk;
}*_