Accessing multiple materials for one GameObject.

I am currently working on a system with multiple materials for one GameObject, but I would like to be able to modify properties of each material through code at runtime.

For the purposes of this example, we will use simply changing a material’s texture on our GameObject for our property to change.

The issue I’m having is the following:

gameObject.renderer.materials[0].mainTexture = (Texture2D)Resources.Load("Tex0Name");
gameObject.renderer.materials[1].mainTexture = (Texture2D)Resources.Load("Tex1Name");

The result is that gameObject.renderer.materials*.mainTexture returns the same texture no matter what you pass in for “i”, causing only one texture to ever be modifiable. Using SetTexture(“_MainTex”, “Tex0Name”) has the same effect. Perhaps I need to access them through the different texture types (_BumpMap, _CubeMap)?*
There is nothing in the Unity documentation discussing this issue, nor how to access a material’s texture directly once applied to a GameObject. Any suggestions would be greatly appreciated.

There’s a problem with renderer.materials: it is a copy of the original array, thus modifications made in its elements don’t affect the actual materials. You must save a copy in a temp array, modify what you want and save it back in materials:

var temp = renderer.materials; // Material[] temp = ... in C# (I guess)
temp[0].mainTexture = ... 
temp[1].mainTexture = ... 
renderer.materials = temp;