How to replace materials in the materials array

I try to replace all materials of an object to make the object transparent.
No problem there with a single material attached to the object:

cachedObject.renderer.material = inReplaceMat;

If I try to access all materials through the materials array though, the material doesn’t change.

cachedObject.renderer.materials[0] = inReplaceMat;

Any Ideas? Am I missing something?


The struct, where I try to do this, for better context:

public struct IntersectingObject{	
	public Material[] cachedMaterial;
	public GameObject cachedObject;
	public IntersectingObject(GameObject inObj,Material inReplaceMat){
		cachedObject = inObj;
		cachedMaterial = cachedObject.renderer.materials;
		for(int i=0; i<cachedMaterial.Length;i++){
			cachedObject.renderer.materials *= inReplaceMat;*

//cachedObject.renderer.materials[0].SetTexture("MainTex",cachedMaterial*.GetTexture("MainTex"));
_
}*

* }*
* public void restore(){*
* for(int i=0; i<cachedMaterial.Length;i++){*
cachedObject.renderer.materials = cachedMaterial*;*
* }
}
}*_

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;*
  •   }*
    
  •   cachedRenderer.materials = intMaterials;*
    

Thanks!! This is exactly what i was looking for

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;
				
		}
	}

in anyone has a better solution please share.

Thankyou