GameObject selectedObject = Selection.activeGameObject;
selectedObject.renderer.Materials[1] = new Material (Shader.Find(" Diffuse"));
Using this gives me an "index out of range" error.
Assigning to sharedMaterials gives me the same error.
What is the proper way to add a new material to the materials array?
*I want to keep the material in index 0 as well, so I will have two materials, one in index 0 and one in index 1.
You can't assign to materials[1], because that slot in memory doesn't exist, if there is only one material. (Only materials[0] exists.) You need to resize the materials arrays somehow. Personally, I'd do it with the array constructor, like this*:
Selection.activeGameObject.renderer.sharedMaterials = new Material[] {
Selection.activeGameObject.renderer.sharedMaterial,
new Material(Shader.Find(" Diffuse"))
};
I probably wouldn't use Shader.Find, actually, as I never seem to have a use for it, but if you do, then this is what I recommend. ;-)