What is the correct way to programatically associate materials with submeshes?

I am building a mesh with submeshes (each submesh potentially has its own material). My understanding is that I need to populate the materials array of the renderer with the same number of materials as submeshes. The code snippet that follows does this, but I get warnings that I am potentially leaking materials into the scene. So I must be doing something wrong. Note, the mesh that I am building is eventually serialized and when it is subsequently loaded again, I don't get the errors, and each submesh has its own material, but I still feel like I am doing something wrong.

So what is the right way to do this?



// now assign triangles and default materials
            if(subMeshIndices.Length == 1)
                mesh.triangles = triangles;
                smRenderer.material = new Material(Shader.Find("Diffuse"));
                mesh.subMeshCount = subMeshIndices.Length;
                CreateSubMeshes(mesh, triangles, subMeshIndices);
                smRenderer.materials = new Material[subMeshIndices.Length];
                for (int j = 0; j < subMeshIndices.Length; ++j)
                    // this line causes a warning each time it is executed
                    smRenderer.materials[j] = new Material(Shader.Find("Diffuse"));

Try using sharedMaterial instead of material