You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity自定义Editor无法获取Item类Name字段出现空引用问题求助

问题根因
  • SerializedObject.FindProperty()参数使用错误:该方法需要传入序列化字段的路径字符串,而非字段的实际值。你当前传入的iteminfo.Name本身就不合法:ItemInfo类没有直接定义Name字段,同时如果Item_Info未赋值,访问成员会直接触发空引用。
  • Item类未标记可序列化:Unity原生序列化系统无法识别未添加[System.Serializable]特性的自定义类,即便路径写对也无法定位到内部字段。
  • 缺少空值校验逻辑:Item_Info未赋值时直接访问其子字段会抛出空引用错误。
修复步骤
  1. 给Item类添加序列化特性,让Unity可以识别该类的内部字段:
[System.Serializable] // 新增该行
public class Item
{
    public string Name, Description;
    public bool stackable;
    public int Value, weight;
    public string ModelPath;
}
  1. 修改自定义编辑器代码,传入正确的序列化路径,同时添加空值校验:
private SerializedProperty itemName;
private ItemInfo iteminfo;

void OnEnable()
{
    iteminfo = (ItemInfo)target;
    // 序列化路径按字段层级用点连接,根字段是ItemInfo里的Item_Info,子字段是Item类的Name
    itemName = serializedObject.FindProperty("Item_Info.Name");
}

public override void OnInspectorGUI()
{
    serializedObject.Update();
    
    if (itemName != null)
    {
        EditorGUILayout.PropertyField(itemName, new GUIContent("道具名称"));
    }
    else
    {
        EditorGUILayout.HelpBox("请先给Item_Info字段赋值后再编辑", MessageType.Warning);
    }
    
    serializedObject.ApplyModifiedProperties();
}
补充说明

如果后续需要在Inspector中展示Item类的其他字段,直接按照Item_Info.对应字段名的格式写路径即可,例:要展示描述字段就传入"Item_Info.Description"。

内容的提问来源于stack exchange,提问作者Sheldon Petry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 07:45:08