Unity序列化对象Inspector中持续出现Argument Null Exception求助
Unity Inspector序列化数组触发Argument Null Exception的排查与修复思路
问题场景
使用自定义序列化对象数组时,修改数组大小为非零后运行游戏,会持续触发Argument Null Exception,停止运行后异常仍不消失,仅重新编译MonoBehaviour类才能终止。
相关代码
序列化对象类
[System.Serializable] public class QObj{ public string myStr; }
MonoBehaviour类
public class QBehaviour: MonoBehaviour { public QObj[] objArr; }
异常调用栈
Parameter name: _unity_self UnityEditor.UIElements.Bindings.SerializedObjectList.get_Count () (at <8ad9ecbe25e14b10b6dde783af6e4aa2>:0) UnityEditor.UIElements.Bindings.EditorListViewController.GetItemsCount () (at <8ad9ecbe25e14b10b6dde783af6e4aa2>:0) UnityEngine.UIElements.VerticalVirtualizationController`1[T].get_firstVisibleIndex () (at <e66f217a64a747d48b478f0d70978704>:0) UnityEngine.UIElements.DynamicHeightVirtualizationController`1[T].Fill () (at <e66f217a64a747d48b478f0d70978704>:0) UnityEngine.UIElements.VisualElement+SimpleScheduledItem.PerformTimerUpdate (UnityEngine.UIElements.TimerState state) (at <e66f217a64a747d48b478f0d70978704>:0) UnityEngine.UIElements.TimerEventScheduler.UpdateScheduledEvents () (at <e66f217a64a747d48b478f0d70978704>:0) UnityEngine.UIElements.UIElementsUtility.UnityEngine.UIElements.IUIElementsUtility.UpdateSchedulers () (at <e66f217a64a747d48b478f0d70978704>:0) UnityEngine.UIElements.UIEventRegistration.UpdateSchedulers () (at <e66f217a64a747d48b478f0d70978704>:0) UnityEditor.RetainedMode.UpdateSchedulers () (at <8ad9ecbe25e14b10b6dde783af6e4aa2>:0)
解决思路
强制刷新编辑器UI绑定
这是Unity UIElements编辑器绑定的常见bug,数组状态变更后SerializedObjectList未正确更新引用:- 切换到其他物体的Inspector面板,再切回目标物体,触发UI刷新
- 点击Inspector右上角菜单,切换到Debug模式后再切回Normal模式,强制重新绑定序列化数据
手动初始化数组元素
Unity有时不会自动初始化数组内的空对象,在QBehaviour中添加初始化逻辑:void OnEnable() { if (objArr == null) return; for (int i = 0; i < objArr.Length; i++) { objArr[i] ??= new QObj(); } }升级/降级Unity版本
该异常多见于2020.x、2021.x的部分子版本,尝试升级到对应大版本的最新补丁,或切换到稳定版本(如2022.x LTS)自定义Inspector规避默认绑定
编写自定义Inspector,绕过Unity默认的UIElements列表绑定逻辑:using UnityEditor; using UnityEngine; [CustomEditor(typeof(QBehaviour))] public class QBehaviourEditor : Editor { public override void OnInspectorGUI() { SerializedProperty arrProp = serializedObject.FindProperty("objArr"); EditorGUILayout.PropertyField(arrProp, true); serializedObject.ApplyModifiedProperties(); } }清除编辑器缓存
清除项目根目录下的Library文件夹(操作前备份项目),重新打开项目以重置序列化缓存
内容的提问来源于stack exchange,提问作者H344Y
相关产品推荐
相关产品推荐

