[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.

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