- Home /
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;
have 3 cubes with different colors.
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.
Also note that you can declare public Renderer cubeRenderer and avoid the call to GetComponent. And you can make your life simpler with arrays i.e. public Renderer[] cubeRenderers. Thus assigning multiple in the editor and being able to iterate through them with a for loop. And do yourself a favor and use a bool for flags ins$$anonymous$$d of an int like you're doing in Change().
@Naphier i have already mentioned
because in loop how you change each object with different colors .so i tried to make it lees code with loops but since you want different colors i did it like this
Answer by Ali-hatem · Apr 20, 2016 at 07:38 PM
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 = Color.green;
rn3.material.color = Color.black;
}
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 .
Thank you very much. Code is working. Can I ask you something else? I want to place and fix my button to somewhere in the 3D scene. But it moves relatively with the character when I press the play button. How can I fix this?
Have you tried setting the canvas to not scale with the view? this should make it work.
I changed the canvas' render mode to World Space and problem is solved. Thanks