How can I compare the sorting layer of 2 gameObjects with different sorting layer names? Screenshot by Lightshot - this is the description for sorting order which means it will only work if I’m comparing within one sorting layer. What if I want to compare in general not only in one? How can I achieve this?
Theres No offical way to compare sorting layers by their render priority , so it is kinda hard to compare them to find out the top most layer.
however you can store each for the names in a public array(which you have to make manually because the sorting layers array is virtually inaccessible), then use that for your comparisons.
e.g
//Get top element out of two
Mathf.Max(array.IndexOf("weather"),array.IndexOf("Overlray"));
Alternatively you can add to a integer to the name referring to its order. this is more of a work around solution and requires String.Format or Regex and each time you reorder you need to name them all again which makes it prone to errors. also the sorting layer Defualt cannot be renamed at all so you have it always on the bottom.
ther higher number refers to the top most
e.g Weather 5, Characters 3, Map 1,
Edit: tested you were right about its ID… So there’s no offical way to compare them without using that alternative solution, if only Sorting layers had a LayerMask class or something.
I made a simple workaround for the problem. I just created a static dictionary with the name of the layers added in the same order as they are in the editor and a method that compares them very easily. For those who might be interestd in how I did it there is the code:
private static Dictionary<string, int> SortingLayers = new Dictionary<string,int>(10);
private void OnEnable()
{
SortingLayers.Add("FirstLayer", 0);
SortingLayers.Add("SecondLayer", 1);
SortingLayers.Add("ThirdLayer", 2);
SortingLayers.Add("FourthLayer", 3);
SortingLayers.Add("RunTimeMenu", 4);
SortingLayers.Add("BlackScreen", 5);
SortingLayers.Add("GameIntro", 6);
}
private static int Compare(GameObject gameObject1, GameObject gameObject2)
{
string layer1 = gameObject1.renderer.sortingLayerName,
layer2 = gameObject1.renderer.sortingLayerName;
return SortingLayers[layer1].CompareTo(SortingLayers[layer2]);
}