Efficient multi-material usage via scripts

Hi there

I’ve got a system that needs to modify a material on an object that has a number of materials applied. From what I can gather, getting the materials via MeshRenderer.materials creates new instances of every one of those materials. Since I only ever want to modify one of the materials and I would prefer to keep the other shared materials intact, is there a way to do this for only one item of the array? Would I have to do something really hacky like

var materials = m_MeshRenderer.materials;
var sharedMaterials = m_MeshRenderer.sharedMaterials;
for (int i = 0; i < materials.Length; ++i)
{
    if (i != indexToKeep)
    {
        Destroy(materials[i]);
        materials[i] = sharedMaterials[i];
    }
}
m_MeshRenderer.materials = materials;

Or is it really not worth worrying about?

Thanks

If you need to do anything material related, use - MaterialPropertyBlock.

It will not make a separate material instance that way.

If it actually has multiple materials, and you want to remove some of them - then I suggest not adding them in the first place. Manage what should be added, add it, and never touch it again.

Alternatively, create an array with materials, and assign it in one go, reuse that array for other renderers too.

Or even non-hacky solution - split your mesh to the separate renderers (its not that hard to do even in blender), then use MaterialPropertyBlock on the mat where modification is needed.

Thanks. I’ll check out the material property blocks. That sounds like what I need.