First, the code works and it does what it should, but the problem is that it doesn’t differ if two or more objects have the same material. It lists all materials, even if the intention is that the same materials do not need to be listed every time if the objects have the same material. It has to do something with the submeshes but I’m not smart enough to handle this.
Here is the code. I have tried everything in between lines 33 and 47 but most of my doings makes whole mesh disappear.
public void CombineMeshesAdvanced(GameObject root)
{
MeshFilter targetFilter = null;
targetFilter = root.GetComponent<MeshFilter>();
//get rotation and position
Quaternion oldRotation = root.transform.rotation;
Vector3 oldPosition = root.transform.position;
root.transform.rotation = Quaternion.identity;
root.transform.position = Vector3.zero;
//create components if not exists
if (targetFilter == null)
{
targetFilter = root.AddComponent<MeshFilter>();
}
MeshRenderer targetRenderer = null;
targetRenderer = root.GetComponent<MeshRenderer>();
if (targetRenderer == null)
{
targetRenderer = root.AddComponent<MeshRenderer>();
}
MeshFilter[] meshFilters = root.GetComponentsInChildren<MeshFilter>();
CombineInstance[] combines = new CombineInstance[meshFilters.Length];
List<Material> materialList = new List<Material>();
for (int i = 0; i < meshFilters.Length; i++)
{
if (meshFilters[i].Equals(targetFilter)) continue; //ignore parent
combines[i].mesh = meshFilters[i].sharedMesh;
combines[i].transform = meshFilters[i].transform.localToWorldMatrix;
Material[] materials = meshFilters[i].GetComponent<MeshRenderer>().sharedMaterials;
foreach (Material material in materials)
{
materialList.Add(material);
}
// Destroy/setactive/etc children
Destroy(meshFilters[i].transform.gameObject);
// meshFilters[i].transform.gameObject.SetActive(false);
}
//create the final mesh
Mesh finalMesh = new Mesh();
finalMesh.CombineMeshes(combines, false);
//create components
MeshFilter filter = root.GetComponent<MeshFilter>();
if (filter == null)
{
filter = root.AddComponent<MeshFilter>();
}
MeshRenderer renderer = root.GetComponent<MeshRenderer>();
if (renderer == null)
{
renderer = root.AddComponent<MeshRenderer>();
}
MeshCollider collider = root.GetComponent<MeshCollider>();
if (collider == null)
{
collider = root.AddComponent<MeshCollider>();
}
//set pos and rot
root.transform.rotation = oldRotation;
root.transform.position = oldPosition;
//components into new mesh
filter.sharedMesh = finalMesh;
collider.sharedMesh = finalMesh;
renderer.sharedMaterials = materialList.ToArray();
}
Image is attached. As we can see, combining meshes has no effect on batches because of all the materials. Setpass calls is though decreasing. Don’t mind the FPS, my laptop is almost 10 years old