- Home /
How can I find all Game Objects in a certain Sorting Layer and dynamically change their position in the Sorting Order?
Hi everyone,
In order to create a sense of depth in my Top-Down 2D Action game, I need to be able to adjust the Sorting Order of various Objects based on their position on the y-axis. So far, I have simply been moving them up and down the z-axis based on their y position, but that has turned out to interfere with another feature.
I'm guessing the most elegant solution would be to build a manager that will find all Game Objects in a specific Sorting Layer and change their Sort Order based on their y-position in the Update function. I'm not sure how performance-taxing this will be, though.
Unfortunately, I'm not very well-versed in C#, so I'm hoping someone can help me out.
Cheers!
I found a more elegant solution, thanks to reddit user /u/Seeders:
public class Obstacle : $$anonymous$$onoBehaviour {
public int offset = 0;
private int scale = 10;
SpriteRenderer sr;
void Start () {
sr = GetComponent<SpriteRenderer>();
}
void Update () {
if (sr)
{
sr.sortingOrder = -((int)transform.position.y + offset) * scale;
}
}
This works, though I don't know how taxing it is.
Your answer
![](https://koobas.hobune.stream/wayback/20220612104458im_/https://answers.unity.com/themes/thub/images/avi.jpg)