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) {
physicalBlocks.Add (physicalBlock);
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;*_