Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

2D top-down sorting layers. How to use sorting group?

Discussion in '2D' started by mrCharli3, Nov 18, 2017.

  1. mrCharli3

    mrCharli3

    Joined:
    Mar 22, 2017
    Posts:
    956
    I have a Script that sorts stuff in my game depending on the y-axis, it's attached to my character and any object I want to render both in front of and behind my character, it looks like this:

    Code (CSharp):
    1. private SpriteRenderer spriteRenderer;
    2.  
    3.     void Start()
    4.     {
    5.         spriteRenderer = gameObject.GetComponent<SpriteRenderer>();
    6.     }
    7.  
    8.     void Update()
    9.     {
    10.         spriteRenderer.sortingOrder = (int)Camera.main.WorldToScreenPoint(spriteRenderer.bounds.min).y * -1;
    11.     }
    Super simple. However, now I have more advanced character, that has several children (all containing sprite renderers) that are body parts, probably 30-ish body parts. As you can imagine this screws up the system I have been using, since I need to use the individual sorting layers to make sure the character is rendered correctly.

    I've been playing around with a sorting group on the parent of the character with more or less the same script but no luck. Surely there must be some way I can solve this?

    Edit:

    Some stuff worth mentioning:
    Sorting group almost works but I dont fully understand it. In order for it to work I add it to the parent, and set its sorting layer to the one that all other object which sort automatically are on.
    This kind of works, but for some reason I need to set the initial value in the sorting group to 290-ish, and if I re-size my screen that value has to be changed. Maybe someone that understands sorting groups can make sense of that.

    Example of what I mean:

     
    Last edited: Nov 20, 2017
  2. mrCharli3

    mrCharli3

    Joined:
    Mar 22, 2017
    Posts:
    956
    Might have solved this, let me get back to you guys
     
  3. Kouznetsov

    Kouznetsov

    Joined:
    Aug 25, 2014
    Posts:
    7
    Did you solve it ? I have a similar issue myself, your solution might guide me.
     
  4. mrCharli3

    mrCharli3

    Joined:
    Mar 22, 2017
    Posts:
    956
    The problem was in my sorting script, and setting the sortingOrder according to the cameras position. If you have a sorting script paste it here and I might be able to help
     
  5. Samacvuk

    Samacvuk

    Joined:
    Jan 8, 2017
    Posts:
    30
    In your workflow, you have to individually add the script to every object that would need to dynamically sort at runtime?
    Sorting groups apparently are a little "buggy".