Change Sorting Layer for a list of elements

Hi
I have a GameObject “Player” which has a lot of children (torso, legs etc.) and I want my script (attached to another GO) to change Sorting Layer of every child. Is it possible to make a list in Inspector, drag there all parts and change Sorting Layer for all of them? Or I have to define every part (32 parts…) separately, define their SpriteRenderer component and change every Sorting Layer separately?

Yes, you can put them all in an array/list. You can even auto-populate the list with something like Reset.

class SpriteRendererContainer : MonoBehaviour
{
   public SpriteRenderer[] allRenderers;

   private void Reset()
   {
       allRenderers = GetComponentsInChildren<SpriteRenderer>();
   }
}

If you attach that to the root of your character, it’ll expose an array with all attached SpriteRenderers already filled in.

Thanks, but how can I change Sorting Layer? I think it would be best to assign a string with a correct name of that Sorting Layer.

So you want to add them to the list and as soon as they are added, change the sorting layer? In editor i guess?

I want to do everything in script. Change Sorting Layer too. Everything I want to do in editor is attach sprites to list.

You can change the sorting layer through the sprite renderer: Unity - Scripting API: Renderer.sortingLayerName

and the sorting order as well: Unity - Scripting API: Renderer.sortingOrder

Finally, I did it! I upgraded Unity from 5.5 to 5.6. There is component called Sorting Group. I’ve attached it to root of these all sprites of player. Then little scripting in script “Cutscenes” (that is why I need it) which is attached to GameObject “GameManager”. The script is

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;

public class Cutscenes : MonoBehaviour {

    public SpriteRenderer[] allRenderers;
    public GameObject playerModel;
    public SortingGroup playerGroup;
    public const string LAYER_NAME = "TopLayer";

    // Use this for initialization
    void Start () {
        allRenderers = GetComponents<SpriteRenderer>();
        playerGroup = playerModel.GetComponent<SortingGroup> ();
    }
 
    // Update is called once per frame
    void Update () {
        //allRenderers.sortingLayerName = LAYER_NAME;
        playerGroup.sortingLayerName = LAYER_NAME;
    }
}

After dragging every component to correct place, this script changes Sorting Layer of player’s model to TopLayer. That’s all.