- Home /
[Sorting Layer] Can I add new sorting layer via script code?
I am trying to manage sorting layers in my C# script.
In my script, I defined the public const string like :
----------------------------------------------------------
public const string Background = "Background";
public const string Item = "Item";
----------------------------------------------------------
then using FiledInfo to get the Name and stringValue and add / overwrite to UnityEditor.
I had already done this to manage my tags and layers definition,
but I don't know how to overwrite / add the new data to sorting layers via script.
please help me, thx.
Answer by virendrakumar531 · Feb 04, 2020 at 12:13 PM
This will only work in Editor
#if UNITY_EDITOR
using UnityEditor;
#endif
#if UNITY_EDITOR
public void addLayer(string layerName)
{
UnityEngine.Object[] asset = AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset");
if ((asset != null) && (asset.Length > 0))
{
SerializedObject serializedObject = new SerializedObject(asset[0]);
SerializedProperty layers = serializedObject.FindProperty("layers");
for (int i = 0; i < layers.arraySize; ++i)
{
if (layers.GetArrayElementAtIndex(i).stringValue == layerName)
{
return; // Layer already present, nothing to do.
}
}
// layers.InsertArrayElementAtIndex(0);
// layers.GetArrayElementAtIndex(0).stringValue = layerName;
for (int i = 0; i < layers.arraySize; i++)
{
if (layers.GetArrayElementAtIndex(i).stringValue == "")
{
// layers.InsertArrayElementAtIndex(i);
layers.GetArrayElementAtIndex(i).stringValue = layerName;
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
if (layers.GetArrayElementAtIndex(i).stringValue == layerName)
{
return; // to avoid unity locked layer
}
}
}
}
}
#endif
Your answer

Follow this Question
Related Questions
Sprite layer order determined by Y value 4 Answers
Problem with Mask and Canvas (Sort Order) Unity 5 1 Answer
Special sprites ordering 1 Answer
Per-Sorting Layer Collision 1 Answer
Render particles in front of any sort layer (2D sprites) 3 Answers