Changing the order in sorting layer of children via c#

I need to be able to change the order in layer of some of my player game object’s children based on the player’s velocity. I have began by assigning the children to variables just after the class declaration:

public GameObject rightLeg;
public GameObject leftArm;
public GameObject leftEar;
public GameObject face;

I now need to store the sprite render components of these children, which I attempted to do in the start event:

leftLegSR = leftLeg.GetComponent;
rightArmSR = rightArm.GetComponent;
rightEarSR = rightEar.GetComponent;

This gives me an error, and this is obviously the wrong way to access the components of children. How should I do it? I want to change the variable in the sprite render named sortingOrder.

You forgot ().

leftLegSR = leftLeg.GetComponent<SpriteRenderer>();
1 Like

You should be able to do it like this:

leftLeg.GetComponent<SpriteRenderer>().sortingOrder++;

The nice thing about sortingOrder is that it’s simply an int, so you can also use the unary operators ++ or – to change sorting layer very easily in a situation like this.

1 Like

Of course! Thank you so much for such fast replies!

No problem. Hope this helps. Feel free to contact me with any more questions regarding the sorting order.