如何通过脚本添加排序层

Hig*_*igh -1 c# unity-game-engine unity-editor

我正在尝试通过脚本添加排序层。

我可以通过脚本添加排序层吗?如何?

Hig*_*igh 5

经过一些测试,我找到了方法。

要添加排序层,我们需要访问它的容器。

Sorting LayerTagManager.asset对象的一部分。(在ProjectSettings目录的相对路径上。)

这段代码可以得到 TagManagerSerializedObject来修改。

var serializedObject = new SerializedObject(AssetDatabase.LoadMainAssetAtPath("ProjectSettings/TagManager.asset"));
Run Code Online (Sandbox Code Playgroud)

要获取SortingLayer数组,我们必须使用以下代码:

var sortingLayers = serializedObject.FindProperty("m_SortingLayers");
Run Code Online (Sandbox Code Playgroud)

我们首先检查我们的目标SortingLayer在数组中不存在。

var layerName = "SomeLayer";

for (int i = 0; i < sortingLayers.arraySize; i++)
{
    if (sortingLayers.GetArrayElementAtIndex(i).FindPropertyRelative("name").stringValue.Equals(layerName))
        return; // this mean target sorting layer exist and we don't need to add it.
}
Run Code Online (Sandbox Code Playgroud)

如果不存在,现在添加它:

sortingLayers.InsertArrayElementAtIndex(sortingLayers.arraySize);
var newLayer = sortingLayers.GetArrayElementAtIndex(sortingLayers.arraySize - 1);
newLayer.FindPropertyRelative("name").stringValue = layerName;
newLayer.FindPropertyRelative("uniqueID").intValue = layerName.GetHashCode(); /* some unique number */
Run Code Online (Sandbox Code Playgroud)

不要忘记申请来源:

serializedObject.ApplyModifiedProperties();
Run Code Online (Sandbox Code Playgroud)

所有顶级代码都可以压缩为波纹管方法:

public static void CreateSortingLayer(string layerName)
{
    var serializedObject = new SerializedObject(AssetDatabase.LoadMainAssetAtPath("ProjectSettings/TagManager.asset"));
    var sortingLayers = serializedObject.FindProperty("m_SortingLayers");
    for (int i = 0; i < sortingLayers.arraySize; i++)
        if (sortingLayers.GetArrayElementAtIndex(i).FindPropertyRelative("name").stringValue.Equals(layerName))
            return;
    sortingLayers.InsertArrayElementAtIndex(sortingLayers.arraySize);
    var newLayer = sortingLayers.GetArrayElementAtIndex(sortingLayers.arraySize - 1);
    newLayer.FindPropertyRelative("name").stringValue = layerName;
    newLayer.FindPropertyRelative("uniqueID").intValue = layerName.GetHashCode(); /* some unique number */
    serializedObject.ApplyModifiedProperties();
}
Run Code Online (Sandbox Code Playgroud)