Change transparency of many Sprites at once.
I'd like to change the transparency of many Sprites at once from within a script. All these Sprites are Children of a parent-object. Can i handle this through this parent? It would be a pain to change all these Sprites one by one, so i guess there is an easy way to do this.
run GetComponentsInChildren() on the parent and save the result. iterate over the array as often as you want to change alpha. within the block, grab the color of each, tune color.a down and reassign.
I think i understood the idea, but i can't figure out how to do this. $$anonymous$$y Code looks like this:
objects = GetComponentsInChildren<SpriteRenderer> (true);
for(int i = 0; i < objects.Length; i++){
float f = objects[i].GetComponent<SpriteRenderer>().color.a;
// Change the alpha here.
}
objects is declared as as a Component array.
Answer by HeaDiii · Sep 09, 2015 at 09:04 PM
Okay i did it. It was a bit hard to understand for me, but i'll explain what i did.
At first i struggled with the reassigning part, because i was only able to get the components of the children. I felt the urge to modify the components of the children themselves, which wasn't possible because i was only able to GET the components, not SET them.
So i saved the SpriteRenders of my Sprites with
SpriteRenderer[] renderer = gameTiles.GetComponentsInChildren<SpriteRenderer> ();
next, i modified my values inside the renderer array. After that, i wanted to reassign the SpriteRenderers to my Sprites like
gameTiles.SetComponentsInChildren ... ;
... which isn't possible of course. Now i just found out, that the SpriteRenderers are some kind of mutable-Datatypes. In programming language you can say, that each instance can have more than one reference and each reference references to the same instance (seems logic). So if you try to change the value stored over one reference, you actually change the value in the instance and as soon as you do that, the values the other references are pointing to are changed as well. Means i am able to do just:
foreach (SpriteRenderer r in renderer) {
r.color = new Vector4 (r.color.r, r.color.g, r.color.b, r.color.a + 0.008f);
}
and i'm fine. No reassigning needed. Working as intended. And yea, that was the part that i was missing. Simple as that.
If i explained something wrong, please correct me.