- Home /
How to change color of multiple objects using C#
I currently have a block by block map. I have some blocks keep the original color, and some blocks turn the object(s) into a red color. However, turning the objects into a red color is a bit of a problem for me.
I am new to C#, and upon hovering over a part with a certain tag, I want the color of multiple objects to change. I have the multiple objects in an Empty GameObject. So I used GetComponentInChildren. However, that only changed one of the colors. Changing it to GetComponentsInChildren throws and error in Visual Basic, and doesn't allow me to play the unity scene. I do not know the correct usage of GetComponentsInChildren().
Here is a section of my script that is relevant to the question:
if (hit.transform.tag == "Bedrock")
{
print("BEDROCK HAS BEEN HIT LOL");
Renderer SelectionColor = Selection.GetComponentInChildren<Renderer>();
SelectionColor.material.color = Color.red;
}
else
{
Renderer SelectionColor = Selection.GetComponentInChildren<Renderer>();
SelectionColor.material.color = Color.red;
}
Any help is appreciated. Thanks!
Answer by Rickasheye · Jan 13, 2018 at 03:03 AM
GameObject[] objects;
public void Start(){
foreach(GameObject j in objects){
j.getComponent<Renderer>().material.color = Color.Green;
}
}
This is an example inside the start method is the actual code pretty much
Here is my code: https://gist.github.com/Vencorr/efdb4562e54458d0ecca19c8493d2670
$$anonymous$$y question now is, how exactly do I properly apply it to the script? In that link is already an attempt. However, in Visual Studio, it says "Use of unassigned local variable 'Sel'". How would I fix this issue? Like I said, I am new to C# and anything would be helpful. I believe I am doing something wrong, of course, but I don't know what.
well the local variable is obviously your array (Sel) and visual studio thinks sel is a single object the code i explained is for an array you can resolve this by adding a new object or make sel an array by adding [] after GameObject then in your method anywhere in start or anywhere else add GameObject[] childObjects = spikes.transform.GetComponentsInChildren(); then with the foreach foreach(GameObject j in childObjects){ //paste here what i said in the last answer //in the foreach part } Btw spikes is an example you would need to replace spikes with sel in the first piece of code
Your answer
![](https://koobas.hobune.stream/wayback/20220612150404im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Material doesn't have a color property '_Color' 4 Answers
Changing two different objects renderer colour 1 Answer
Change Color in C# with RGB Values? 4 Answers
Changing Game Objects Color 1 Answer
Change skybox color via script? 0 Answers