How to replace element in MeshRenderer.sharedMaterials

We are using a object from the asset store that makes usage’s of a mesh renderer with 32 materials in it. We need to implement functionality that makes it possible to replace 1 single material in the list, and keep the rest.

I have tried several things, but I keep struggeling with the materials list, that is why I decided to ask you guys for help.

public Material TestMaterial;

void Update()
{
       for (int i = 0; i < meshRenderer.sharedMaterials.Length; i++)
       {
       if (meshRenderer.sharedMaterials[i].name == "replaceableMat")
       {
             // Replace with TestMaterial
       }
       }
}

The above code is how I kinda want to use it.

The TestMaterial object is not null, it is selected from the Unity Editor, so that is fine.

Could someone give me some insight?

Thanks in forward!

From the docs, it sounds like you can just modify this array and assign it back.

var mats = meshRenderer.sharedMaterials;
mats[7] = someOtherMaterial;
meshRenderer.sharedMaterials = mats;
1 Like