- Home /
Add SortingLayer by script
hello i need to create dynamically sorting layers by code (C#). then i can get its ID and give to a sprite.
i need to do this since i have no idea what is the exact number of the sprites, and each sprite HAS to have its own sorting layer
PS: not a normal Layer, but the Sorting Layer
i tried:
SortingLayer sl = new SortingLayer ();
sl.name = "something";
sl.id = 12;
but obviously this does not work. any help?
Answer by gnumaru · Jul 05, 2018 at 10:52 AM
Something like this should work (editor only)
SerializedObject tagsAndLayersManager = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset")[0]);
SerializedProperty sortingLayersProp = tagsAndLayersManager.FindProperty("m_SortingLayers");
sortingLayersProp.InsertArrayElementAtIndex(sortingLayersProp.arraySize);
var newlayer = sortingLayersProp.GetArrayElementAtIndex(sortingLayersProp.arraySize);
newlayer.FindPropertyRelative("uniqueID").intValue = UnityEngine.Random.Range(int.MinValue, int.MaxValue);
newlayer.FindPropertyRelative("name").stringValue = "my new layer";
tagsAndLayersManager.ApplyModifiedProperties();
I wrote code based on what you posted and it works perfectly! Thank you! However, I would like to save my changes (right now they are jumping back to what it was before after I exit play mode).
This method is meant only for use at editor time, editing projectsettings in play mode is not possible, and will always revert back once play mode is exited.
Answer by hfiani · Aug 20, 2017 at 03:25 PM
no one knows the answer to this question? i searched a lot but found nothing
What you are trying to do is not possible exactly as described because sorting layers are part of projectsettings and not modifiable at runtime. What you are allowed to do however is change the sortingOrder dynamically which will do the same thing.
I assume you are re-sorting SpriteRenderer components at runtime to move objects visually in render order. That can be achieved easily like so: SpriteRenderer spriteRenderer = someObject.GetComponent(); spriteRenderer.sortingOrder = 10;
Answer by Nadogeto · Jan 17 at 03:39 PM
here's an appropriate and functional answer, if anyone is still out there searching
Your answer
