- Home /
Make ALL gameObjects in an array do the same thing with one line of code
I am making a game with 50 different regions that all change color when I press a button. They all change to the same color too. To easily load these 50 regions into a script, I have made an array that finds all GameObjects tagged with "Region".
public GameObject[] stateDataArray;
void Start ()
{
stateDataArray = GameObject.FindGameObjectsWithTag("Region");
}
I have my array and all my GameObjects in it, but now for me to change all their colors I need to make 50 lines of the same code.
stateDataArray[0].GetComponent<SpriteRenderer>().color = Color.red;
stateDataArray[1].GetComponent<SpriteRenderer>().color = Color.red;
stateDataArray[2].GetComponent<SpriteRenderer>().color = Color.red;
stateDataArray[3].GetComponent<SpriteRenderer>().color = Color.red;
stateDataArray[4].GetComponent<SpriteRenderer>().color = Color.red;
I want to make it all in one line, like this.
stateDataArray[ all of the objects in my array ].GetComponent().color = Color.red;
I know there has to be away to make this simpler, I just haven't been able to find it yet.
C# please. Thanks in advance.
for(int i = 0; i < stateDataArray.Length; i++) stateDataArray[i].GetComponent<SpriteRenderer>().color = Color.red;
Technically this is one line. I recommend you write in in three anyway. :)
Well, technically you can:
stateDataArray.ToList().ForEach (x => x.GetComponent<SpriteRenderer> ().color = Color.red);
But don't really do it unless you understand it and the performance implications.
Answer by JSierraAKAMC · Nov 30, 2014 at 08:00 AM
Well, I don't believe you can do it in just one line, but you can do it in 3 (or fewer if you format it differently):
for(int i = 0; i < stateDataArray.Length; i++){
stateDataArray[i].GetComponent<SpriteRenderer>().color = Color.red;
}
Alright thanks, this does exactly what I wanted to. actually bored$$anonymous$$ormon did it first but I don`t want to answer my own question.
Answer by TukangSendal · Nov 05, 2019 at 07:10 AM
u can with foreach
foreach(GameObject data in stateDataArray){
data.GetComponent<SpriteRenderer>().color = Color.red;
}