Handle order in layer in 2D game ?
Hi everybody,
I'm currently developing a new game for learning Unity2D. I'm trying to implement a 2.5D (is it really a 2.5D?) game type and I'm facing an issue concerning "order in layer".
Let's take an example. I have two game component :
- Player which have 2 in "order in layer" 
- Crate which have 3 in "order in layer" 
So if Player moves behind the crate, it's OK as you can see (admire this unique visual style) :

But if Player moves in front of the crate, it's weir because the player seems to be "behind" it, as you can see : 
If I manually change the player order to 4, it's OK. So here is my question :
How can I dynamically handle the player layer order depending on the Y axis, bearing in mind that the Y axis range which the player can move may vary because my level can go up and down ?
Thank you in advance for your help.
Answer by TntManiak · Nov 20, 2015 at 08:07 AM
After all I managed to dynamically modify sorting order using Y value of objects. The script must receive of course a lot of improvements but here is the idea.
 using UnityEngine;
 using System.Collections.Generic;
 using System.Linq;
 
 public class SortingLayerManagement : MonoBehaviour {
 
     private List<Transform> transforms;
 
     // Use this for initialization
     void Start () {
         transforms = new List<Transform>();
         
         for (int i = 0; i < transform.childCount; i++)
         {
             Transform child = transform.GetChild(i);
 
             if (child.GetComponent<SpriteRenderer>() != null)
             {
                 transforms.Add(child);
             }
         }
     }
     
     // Update is called once per frame
     void Update () {
 
         // Tri les enfants par position
         transforms = transforms.OrderByDescending(
             t => t.FindChild("PerspectivePoint").position.y
             ).ToList();
 
         int layerOrder = 0;
         foreach (Transform child in transforms) {
             child.GetComponent<SpriteRenderer>().sortingOrder = layerOrder;
 
             layerOrder++;
         }
     }
 }
Answer by Dinosaurs · Nov 19, 2015 at 04:29 PM
You can either treat your game as 3D rather than 2D and position sprites Z position yourself rather than using layers, or run a script that checks the Y value of game objects against the player and moves them accordingly.
Thank you for your advices, I finally come with a solution which approximates your second proposal.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                