Merging meshes

Hi Everyone,
i’m trying to merge meshes with different material on a single mesh with different submeshes associated: every mesh i try to merge is considered as a single submesh of the new generated gameobject, each with the original material. Here my code:

    public void Merge(GameObject[] gameObjects, string Name)
    {
        if (gameObjects.Length == 0) return;

        Material[] materials;
        MeshFilter[] meshFilters = new MeshFilter[gameObjects.Length];
        MeshRenderer[] meshRenderers = new MeshRenderer[gameObjects.Length];
        Mesh combinedMesh = new Mesh();
        combinedMesh.subMeshCount = gameObjects.Length;
        int size = 0;

        for (int i = 0; i < gameObjects.Length; i++)
        {
            meshFilters _= gameObjects*.GetComponent<MeshFilter>();*_

meshRenderers = gameObjects*.GetComponent();*
size = meshRenderers*.sharedMaterials.Length + size;*
}
materials = new Material;
CombineInstance[] combine = new CombineInstance[gameObjects.Length];

for (int i = 0; i < gameObjects.Length; i++)
{
int j;
if (i == 0)
{
j = 0;
}
else
{
j = meshRenderers[i - 1].sharedMaterials.Length;
}
combine*.subMeshIndex = i;*
combine_.mesh = meshFilters*.sharedMesh;
combine.transform = meshFilters.transform.localToWorldMatrix;_

_for (int k = 0; k < meshRenderers.sharedMaterials.Length; k++)
{_

_materials[j + k] = meshRenderers.sharedMaterials[k];
}*_

}

combinedMesh.CombineMeshes(combine);
AssetDatabase.CreateAsset(combinedMesh, “Assets/” + Name + “.asset”);
GameObject combinedObject = new GameObject(Name);
var filter = combinedObject.AddComponent();
filter.sharedMesh = combinedMesh;
var renderer = combinedObject.AddComponent();
renderer.sharedMaterials = materials;
}
#endregion
unfortunately i’m not able to have the final gameobject with all the preexisting materials of each mesh to merge: could someone help me in this?
Thanks a lot,

It is possible to combine meshes with different materials using the “Easy Mesh Combiner MT” tool, available in the Asset Store. It is able to combine meshes and even generate Atlases or not. You can even do runtime merges. It’s worth checking out! Here is the link: Easy Mesh Combiner MT - Scene Mesh Merge, Atlasing Support & More | Game Toolkits | Unity Asset Store