1
\$\begingroup\$

I would like to set programatically the material on a Game Object. The problem is that it has several Child Objects, which many have their own sprite.

I came up with this...

    foreach(Transform child in enemy.transform) {

        SpriteRenderer _spriteRenderer = child.GetComponent<SpriteRenderer>();

        if (_spriteRenderer) {
            _spriteRenderer.material = ...;
        }

    }

...which works, but it is not very pretty. Is there a better way to do this?

Update: I know about GetComponentsInChildren but I need to also get the GameObject that are disabled

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

See the documentation for GetComponentsInChildren:

public Component[] GetComponentsInChildren(Type type, bool includeInactive = false);

This states you can use the boolean includeInactive in GetComponentsInChildren to also get the inactive components. This way you can grab all the transforms. Even inactive ones. So you would probably want to do this:

//Create an array of SpriteRenderers
SpriteRenderer[] _spriteRenderers;
void Start ()
{
  _spriteRenderers = transform.GetComponentsInChildren<SpriteRenderer>(true); //This returns an Array
   //Change the material on all the Sprite Renderers.
   for (int i = 0; i < _spriteRenderers.Length; i++)
   {
     _spriteRenderers[i].material = ...;
   }
}
\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .