How Can I Make Sprite Sorting Layers 'Relative'?
Hello, I'm currently working on a modular weapon system for my project. My Game is a top-down, 2D roguelike, and so I put all of the gameobjects which need to interact with one another in terms of rendering order under the same sorting layer of "Interactibles" and render them in order depending on their Y-coordinate. The problem is that once I apply a weapon (which is assigned to a Transform position childed to the player), I want it to appear behind the player, but in front of everything else. So all of the objects are on the same sorting and order in layer, yet I need to somehow make the weapon, once equipped, to always render behind the player that equipped it yet in front of all other objects on the same layer. Is there any way to do something like this? (The images illustrate how the weapon renders in front or behind the player / other objects like in the attack animation) Any help is appreciated
Answer by diego-giacomelli · Nov 14, 2020 at 12:45 AM
You need to use a Sorting Group on the Player:
Sorting Groups allow you to group GameObjects with Sprite Renderers together, and control the order in which they render their Sprites. Unity renders Sprite Renderers in the same Sorting Group together, as if they are a single GameObject.
The sample showing in the docs is similar to your problem:
[3]: https://docs.unity3d.com/uploads/Main/unique_orderlayer.png
If I put a sorting group on the top object the weapon then sometimes renders in front of the player or behind it, depending on the weapon position. I tried using the sorting groups but regardless of the organization I use (I tried separating the player body and weapon position, controlling the sorting layer through animation events, etc), the weapon always renders either in front of the player, behind the walls, or is inconsistently doing both. The only real solution I see is somehow getting layer "Weapon" to render behind Layer "Player" which would render with Layer "Walls", yet having Layer "Weapon" somehow still render in front of Layer "Wall" subsection of the interactibles layer