c# - 二维布尔数组上的 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 上的第一个问题,我尽量遵循指南,但如果我在问题中犯了任何错误,我深表歉意。
解决方案
似乎它为 null 的原因是 Unity 中序列化属性的限制。例如,如果属性是一个整数数组,它引用 SerializedProperty.intValue 中的第一个元素,并具有 isArray、arraySize 等,让您知道它实际上是一个数组。当它是一组数组时,它就会崩溃。因此,我能找到的最佳解决方案是将一维数组视为二维数组,这不是很优雅,但数据结构无论如何都非常抽象。因此,再次提醒遇到同样问题的人,API 说数组都很好,但这意味着一维数组。
推荐阅读
- sql - 数据库查询未按要求运行
- windows - 使用 PowerShell Studio 在 cmd 中执行“where”命令
- java - 如何在 Linux 上的 Intellij 中逐步正确安装 java 和 javafx?
- java - 如果在 java 中的并发映射之外修改对象会发生什么?
- python - 如何在 Python 的 OpenPyxl 旁边使用 R 的 Reticulate 包来隐藏 excel 中的行
- python - 修复“AttributeError:模块'pandas.compat'没有属性'string_types'”错误
- pine-script - RSI 高于/低于先前柱交易视图 Pines 脚本
- docker - 如何设置 google cloud Cloudbuild.yaml 来复制 jenkins 作业?
- oracle - 如何在 Oracle PLSQL 中声明 Windows 路径
- android - 使用 APK 跟踪应用程序安装推荐