首页 > 解决方案 > 二维布尔数组上的 SerializedObject.FindProperty() 返回 null

问题描述

我目前正在 Unity 中为具有需要设置的 2D 布尔数组的类开发自定义编辑器。但是,每当我尝试使用 SerializedObject.FindProperty() 设置值时,返回的值为 null 并且出现错误。当我尝试通过 SerializedObject.targetObject 直接设置它们时,布尔值仅针对 OnGui() 的调用发生变化,并且在我调用 SerializedObject.ApplyModifiedProperties() 时不保存,因为它知道知道它们已更改的方式。

private void OnGUI()
{
    serializedObject.Update();

    GUILayout.Label(serializedObject.targetObject.name + " - Spawn Options", EditorStyles.boldLabel);

    EditorGUIUtility.labelWidth = 60;
    indexSize = EditorGUILayout.DelayedIntField(new GUIContent("Array Size"), indexSize, GUILayout.ExpandWidth(false));

    serializedObject.FindProperty("gameObjects").arraySize = indexSize;
    LevelGenerator target = (LevelGenerator)serializedObject.targetObject;
    target.spawnLocations = new bool[indexSize, target.areas.Count];

    EditorGUILayout.Space();


    for (int i = 0; i < indexSize; i++)
    {
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.ObjectField(serializedObject.FindProperty("gameObjects").GetArrayElementAtIndex(i));

        var labels = target.areas.Keys;
        for(int j = 0; j < target.areas.Count; j++)
        {
            target.spawnLocations[i, j] = EditorGUILayout.Toggle(labels.ElementAt(j), target.spawnLocations[i, j]);

            if(target.spawnLocations[i, j])
            {
                Debug.Log("set for one loop at least");
            }

            EditorGUILayout.PropertyField(
                serializedObject.FindProperty("spawnLocations").GetArrayElementAtIndex(i).GetArrayElementAtIndex(j), 
                new GUIContent(labels.ElementAt(j)));
        }

        EditorGUILayout.EndHorizontal();
    }

    serializedObject.ApplyModifiedProperties();
}

这是我在 StackOverflow 上的第一个问题,我尽量遵循指南,但如果我在问题中犯了任何错误,我深表歉意。

标签: c#unity3dunity-editor

解决方案


似乎它为 null 的原因是 Unity 中序列化属性的限制。例如,如果属性是一个整数数组,它引用 SerializedProperty.intValue 中的第一个元素,并具有 isArray、arraySize 等,让您知道它实际上是一个数组。当它是一组数组时,它就会崩溃。因此,我能找到的最佳解决方案是将一维数组视为二维数组,这不是很优雅,但数据结构无论如何都非常抽象。因此,再次提醒遇到同样问题的人,API 说数组都很好,但这意味着一维数组。


推荐阅读