我目前正在 Unity 中为一个类开发自定义编辑器,该类具有需要设置的二维 bool 值数组。但是,每当我尝试使用 SerializedObject.FindProperty() 设置值时,返回值为 null 并且出现错误。当我尝试通过 SerializedObject.targetObject 直接设置它们时,bools 仅在调用 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 上提出的第一个问题,我尽量遵循指南,但如果我在问题中犯了任何错误,我深表歉意。
最佳答案
似乎它为 null 的原因是 Unity 中序列化属性的限制。例如,如果该属性是一个整数数组,它会引用 SerializedProperty.intValue 中的第一个元素并具有 isArray、arraySize 等,让您知道它实际上是一个数组。当它是一个数组数组时,它就会分崩离析。所以我能找到的最好的解决方案是像对待二维数组一样处理一维数组,这不是很优雅,但无论如何数据结构都非常抽象。因此,作为对遇到相同问题的任何人的警告,API 说数组都很好,但这意味着一维数组。
关于c# - 二维 bool 数组上的 SerializedObject.FindProperty() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52974594/