- Home /
How do I store the colors of children in an array?
Okay, so I'm trying to script in a little code that will make an enemy in my game flash red when I attack them. I already have figured out how to make them turn red:
foreach (Renderer r in GetComponentsInChildren ()) { r.material.color = Color.red; }
but I can't think of a way to make them return to their original colors. I was thinking I could store each children's original color in an array but I don't know a good way to do that. Please help
Answer by MacDx · Oct 27, 2017 at 06:09 PM
You already know how to get the renderers that contain the colors. You just need declare an Color array variable and store the colors there before changing them to red. Do something like this:
 //Get ahold of the renderers
 Renderer[] renderers = GetComponentsInChildren<Renderer>();
 
 //Declare a color array
 Color[] originalColors = new Color[renderers.Length];
 
 //Save the original colors into the array
 for(int i = 0 ; i<originalColors.Length ; i++)
 {
     originalColors[i] = renderers[i].maetrial.color;
 }
 //Now that the original colors are saved you can change the color to red
 
 foreach(Renderer r in renderers)
 {
     r.material.color = Color.red;
 }
 
 //EDIT: If this code is inside a coroutine then you can do
 // yield return new WaitForSeconds(0.5f);
 
 //And then when you want to turn them back to the original color you just do
 for(int i = 0; i<originalColors.Length; i++)
 {
     renderers[i].material.color = originalColors[i];
 }
 
Note that in this code I wrote, renderers and originalColors are local variables, but you could easily turn them into fields instead so you can use them elsewhere in your code, or if you are already using a coroutine for this code then you could just yield for some time and use them as they are here.
I am getting an error saying that "Object reference not set to an instance of an object" at the start of the four loop that changes the colors back. Any suggestions?
This is either an error in your renderer list or your color list. Try printing the length of each list before running the loop to see what has fewer instances.
Even better, make your arrays temporarily public and observe them in the inspector when the error is thrown. That way you can figure it out clearly.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                