How to change multiple objects' material (color) with one button?

I’ve searched most of the community questions and answers related to this topic and also youtube tutorials. But I couldn’t find my answer. Here is the problem;

-I have 3 cubes with different colors.
-I want to add a button that will change all of their colors in the first click. Then, in the second click, colors will return to their first state. It can be toggle, too.

If there is a youtube tutorial or something else, I’m eager to see them also.

so i tried to make it lees code with loops but since you want different colors i did it like this

int counter = 0;
public GameObject Cube1;
public GameObject Cube2;
public GameObject Cube3;
Renderer rn1;
Renderer rn2;
Renderer rn3;
Color  col1;
Color  col2;
Color  col3;

void Start(){
	rn1 = Cube1.GetComponent<Renderer>();
	rn2 = Cube2.GetComponent<Renderer>();
	rn3 = Cube3.GetComponent<Renderer>();
	col1 = rn1.material.color;
	col2 = rn2.material.color;
	col3 = rn3.material.color;
public void Change(){
	if (counter == 0) {
		newColor ();
		counter = 1;
	} else {
		oldColor ();
		counter = 0;
void oldColor(){
	rn1.material.color = col1;
	rn2.material.color = col2;
	rn3.material.color = col3;
void newColor(){
	rn1.material.color = Color.gray;
	rn2.material.color =;
	rn3.material.color =;

also i am getting weird warning “UnassignedReferenceException : The variable Cube1 of Control has not been assigned.” even after assigning all cubes in inspector but every thing work fine i hop it’s a bug .