My quick solution to sorting issues in Unity

I’m making a pseudo 2d game in unity. Its a 2d top down game, but the camera is perspective and at an bit of an angle, and the sprites are tilted to face the camera.

I’m using sprites and have run into issues with sorting. You cant have sublayers, so eg. if you put ‘face’ of character above ‘body’ of character, then a character who is behind another characters face will show through thr character in front.

I threw together these two scripts to solve the problem.
It works but I have no idea what performance impact it will have (I havent profiled it yet)

Is there a better solution to this problem?
What performance impact do you think my solution will have??

All the sprites are on the same sorting layer, I’m using these scripts to manually set their sortingOrder each frame.
I put this monobehaviour on all my characters, and drop all its sprite renderers onto it, in order, from back to front

public class Sort : MonoBehaviour
{
public SpriteRenderer[ ] Rens;

void Start()
{
Refs.Ref._SortAll.Sorters.Add(this);
}

void OnDestroy()
{
Refs.Ref._SortAll.Sorters.Remove(this);
}

public int SortEm(int index)
{
foreach (var ren in Rens)
{
ren.sortingOrder = index;
index++;
}
return index;
}
}

Then this monobehvior is in the scene. It sorts them all by their Y value (ones with lower Y are closer to the camera)

public class SortAll : MonoBehaviour
{
public List Sorters = new List();

// Update is called once per frame
void Update ()
{
Sort[ ] SortedByY = Sorters.OrderBy(o => -o.transform.position.y).ToArray();

int index = 0;

foreach (var sort in SortedByY)
{
index = sort.SortEm(index);
}
}
}

Well, one thing you could change is the creation of a new array each frame. I would probably keep them all in one array and sort them manually. You can see the impact of this in the profiler window’s “CPU Usage” (“GC Alloc” column).

1 Like