After experimenting a lot I finaly found the solution to the problem: renderer.materials gives just a copy of the materials array, not a reference. Changing the materials in it doesn’t have any effect on the actual materials of the renderer.
What works is to substitute the whole array at once with a new preconfigured materials array:
intMaterials = new Material[cachedMaterial.Length];
for(int i=0; i<intMaterials.Length;i++){
intMaterials *= inReplaceMat;*
in case this helps anyone, solution for bunch of renderers with each one having bunch of materials.
private Dictionary<Renderer, Material[]> originalMaterials = new Dictionary<Renderer, Material[]>();
void Awake ()
{
//children is a reference to the renderers
children = GetComponentsInChildren<Renderer>();
foreach (Renderer rend in children)
{
//make array of all materials in renderer
Material[] materials = rend.materials;
//add to dictionary renderer and material
originalMaterials[rend] = materials;
}
}
void ChangeToNewMaterial()
{
foreach (Renderer rend in children)
{
var mats = new Material[rend.materials.Length];
for (var j = 0; j < rend.materials.Length; j++)
{
mats[j] = newMaterial;
}
rend.materials = mats;
}
}
void Reset()
{
foreach (KeyValuePair<Renderer, Material[]> pair in originalMaterials)
{
pair.Key.materials = pair.Value;
}
}