I am not much of an expert, tried to look up for solutions but I never found any that I could use.

I have a parent object, and I want to change it's child objects randomly. This is the hierarcy: hierarchy

I want to change both the "Roof" and the "Building" sprites randomly. This is how my code looks like right now:

public Sprite[] sprites;

void Update()

public void RandomizeSprites()
    random = Random.Range(0, sprites.Length);
    GetComponentInChildren<SpriteRenderer>().sprite = sprites[random];

This currently only works for the first child object.

Can anyone help me how to do it for both? Thank you in advance!

  • \$\begingroup\$ Do you have a separate set of sprites to use for the roof, versus the building, or should they both draw from the same pool of sprites (so sometimes you could get the same sprite chosen for both the roof and building parts)? \$\endgroup\$
    – DMGregory
    Oct 6, 2022 at 21:37
  • \$\begingroup\$ Thank you for your reply! It doesn't matter if the sprites match or not, since they have all the same size. All I'd like is picking a random roof and a random building sprite whenever a new "platform" get spawned. \$\endgroup\$
    – imbruceter
    Oct 6, 2022 at 22:45

1 Answer 1


In the Start() function, store all of your child object building and roofs into a SpriteRenderer Array with

SpriteRenderer[] renderers;

void Start(){
    //GetComponents with an S collects all  children of that type.
    //Now loop through the array and apply a random sprite

    foreach (SpriteRenderer ren in renderers) {
        //Sprite ransomsprite = select random sprite however
        ren.sprite = randomsprite;

No need to use the update function if you are doing this when they spawn.

You can have a separate list of sprites for buildings and one for roof if needed and draw a random one accordingly for each.

You can differentiate between roof and building by checking

if(ren.name == "Roof")
ren.sprite = roofsprites[random];
  • \$\begingroup\$ If you want to distinguish roof vs building sprites, I'd recommend making named inspector variables for the two SpriteRenderers, that way you save the runtime search and allocation of an array at start-up, and someone changing a name in the scene/prefab won't break your code. \$\endgroup\$
    – DMGregory
    Oct 7, 2022 at 12:30

You must log in to answer this question.

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