1. ホーム
  2. c#

[解決済み] EditorGUILayout.ObjectFieldが参照を受け取らない

2022-02-24 13:06:14

質問

カスタムエディターを勉強中です。その 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);

    }
}

解決方法は?

を再定義しているのですね。 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);    
        }
    }
}