EditorGUILayout.ObjectField没有收到参考

时间:2018-04-04 21:55:00

标签: c# unity3d

我正在学习自定义编辑器。显示ObjectField,可以将Inventory脚本或包含它们的GameObjects拖到广告位中。但什么时候掉线没什么事。该区域亮起,但掉落的物体不会粘住。

当我按下按钮targetnull时。

public class AddInventory : EditorWindow {

    public Inventory target;

    [MenuItem("Inventory/Add items")]
    public static void ShowWindow()
    {
        GetWindow<AddInventory>("Add items");
    }

     void OnGUI()
    {
        GUILayout.Label("Add items to  inventory", EditorStyles.boldLabel);
        Inventory target = null;
        target = (Inventory) EditorGUILayout.ObjectField("Inventory thingy", target, typeof(Inventory), true);


        if (GUILayout.Button("I am button!"))
        {
            Debug.Log(target.thing);

        }
    }
}

我也尝试了每个建议:

   void OnGUI()
{

    GUILayout.Label("Add items to  inventory", EditorStyles.boldLabel);

  var  myInventory = (GameObject) EditorGUILayout.ObjectField( myInventory, 
     typeof(GameObject), true);


    if (GUILayout.Button("I am button!"))
    {
        Debug.Log(myInventory.name);

    }
}

1 个答案:

答案 0 :(得分:1)

您正在重新定义target。从Inventory target = null;移除OnGUI()行,并确保您的Inventory班级当然是Unity Object以使用ObjectField

public class AddInventory : EditorWindow {

    public Inventory target;

    [MenuItem("Inventory/Add items")]
    public static void ShowWindow()
    {
        GetWindow<AddInventory>("Add items");
    }

     void OnGUI()
    {
        GUILayout.Label("Add items to  inventory", EditorStyles.boldLabel);

        target = (Inventory)EditorGUILayout.ObjectField("Inventory thingy", target, typeof(Inventory));   

        if (GUILayout.Button("I am button!"))
        {
            Debug.Log(target.thing);    
        }
    }
}