How do I control Opacity of multiple objects at same time with GUI slider?

I have an object that is made up of multiple pieces and I am trying to change the opacity of all of them at the same time with one GUI slider. I use the following script successfully on one object, but when I attach it to more than one it only works on one object at a time.

Script:
var slider : float;

function OnGUI () {
 
   slider = GUI.HorizontalSlider( Rect(20,135,175,30), slider, 0.0, 1.0);
 
   renderer.material.color.a = slider;
 
}

Have a script attached to your camera or an empty gameobject that handles the opacity of all the objects you want.

So your script attached to your camera would look like this…

var object1 : GameObject;
var object2 : GameObject;
var object3 : GameObject;

function OnGUI () {

   slider = GUI.HorizontalSlider( Rect(20,135,175,30), slider, 0.0, 1.0);

   object1.renderer.material.color.a = slider;
   object2.renderer.material.color.a = slider;
   object3.renderer.material.color.a = slider;
}

Then make sure to assign object1, 2 and 3 in the inspector.

Thanks a lot!!! I am new to .js so this was a huge help.

Thx!!!

EDIT: Presuming all your GameObjects are using the SAME material:

Use Renderer.sharedMaterial instead. All objects using this material will be permanently affected, hence I strongly recommend creating a new dedicated material before playing with this method.

If I understand your problem correctly, this is probably the easiest way to achieve your goal, if you understand the risks involved.