I procedurally generate chunks and use the marching cube algorithm to create meshes in 3D.
At first, I just created a gameObject for each cube (of course, I knew it was not optimized, but I wanted to see if the algorithm worked).
For now I stock all gamesObject in child of "blocks" but it would be much more optimized to directly merge the meshes between them and only create a single gameObject.
However, i did not find any way to directly merge the meshes between them.
So my question is: is there a way to directly merge meshes between them without having to use gameObject? (don't worry about texturing)
Here's the code:
public static GameObject GenerateChunk(int[,,] map, int chunkSize, Vector3 chunkPosition)
{
GameObject blocks = new GameObject("BlockList");
GameObject newMesh;
int[] cubeVertices = new int[8];
// create each mesh in a gameObject as child of "blocks"
for (int x = 0; x < chunkSize; x++)
for (int z = 0; z < chunkSize; z++)
for (int y = 0; y < chunkSize; y++) {
/*
define the vertices (cubeVertices)
*/
Vector3 cubePosition = new Vector3(chunkPosition.x + x, chunkPosition.y + y, chunkPosition.z + z);
newMesh = GenerateCube(cubePosition, cubeVertices);
if (newMesh != null)
newMesh.transform.parent = blocks.transform;
}
//combine every children of "blocks" and delete them
MeshFilter[] filters = blocks.GetComponentsInChildren<MeshFilter>();
List<CombineInstance> combine = new List<CombineInstance>();
for (int i = 0; i < filters.Length; i++) {
if (filters[i].sharedMesh == null)
continue;
for (int j = 0; j < filters[i].sharedMesh.subMeshCount; j++) {
CombineInstance ci = new CombineInstance
{
mesh = filters[i].sharedMesh,
subMeshIndex = j,
transform = filters[i].transform.localToWorldMatrix
};
combine.Add(ci);
}
Destroy(filters[i].gameObject);
}
//create the chunk and set the final mesh with the CombineMeshes function
GameObject chunk = new GameObject("Chunk", typeof(MeshFilter), typeof(MeshRenderer));
chunk.GetComponent<MeshFilter>().mesh.CombineMeshes(combine.ToArray(), true, true);
Destroy(blocks);
return chunk;
}