Combining duplicate Materials at run time

I’ve got a process that generates a bunch of meshes at runtime each of which has a simple diffuse material with just a diffuse colour, no texture maps or anything.

After all the meshes have been loaded, they are all combined, and the result is a single mesh, with ~20-30 different materials.

of these, there are probably about 5 unique.

I’d like to loop through all of the materials, find unique ones by simply comparing shaders/colors and replace any instances that match with the single sharedmaterial.

as a simple test i’m simply trying to assign all materials within the mesh to a single sharedmaterial, but havn’t been able to get it to work.

materialsArray = meshRendererCombine.sharedMaterials;
        var ShMat : Material = meshRendererCombine.sharedMaterial;
        for (i = 0; i < materialsArray.length; i++) {
            materialsArray[i] = ShMat;
        }
        meshRendererCombine.sharedMaterials = materialsArray;

ShMat.color = Color(.4,1,.4);

by changing ShMat’s colour, everything changes.
But if i change the colour of one of them in the inspector, only the single part changes.

if i manually drag one of the Materials into the various array slots in the Inspector, then change its color, it works as expected.

Assigning materials to this array obviously doesn’t work how i expect, any help would be appreciated.

ok!

stumbled apon the issue, the process was doing all of the combining, then changing scene.
as part of initializing the next scene, it was assigning a cube map using .materials

so once it hit the next scene, the materials were all split out again!