Search Unity

Get object from EditorGUILayout.PropertyField

Discussion in 'Immediate Mode GUI (IMGUI)' started by Retruate, Apr 30, 2016.

  1. Retruate

    Retruate

    Joined:
    Jul 5, 2014
    Posts:
    111
    Hi,

    I'm making a plugin-manager extension to the Unity Editor. I need an ObjectField to drag-and drop folders in, and so far this has worked

    Code (CSharp):
    1. public override void OnInspectorGUI()
    2.     {
    3.         serializedObject.Update();
    4.         //...
    5.         if (Event.current.commandName == "ObjectSelectorUpdated")
    6.         {
    7.             currentObject = EditorGUIUtility.GetObjectPickerObject();
    8.         }
    9.  
    10.         currentObject = EditorGUILayout.ObjectField("Object", currentObject, typeof(Object), true) as DefaultAsset;
    11.         //...
    12.         serializedObject.ApplyModifiedProperties();
    13.     }
    Yet, I need this to be a re-sizable list of ObjectFields, and not just one.

    Using
    Code (CSharp):
    1. EditorGUILayout.PropertyField(folderProp, new GUIContent("Plugin 1"), true);
    2.         //"folderprop" is a serialized property of "Object[]".
    gives me my re-sizable list in the inspector, but I don't know how to retrieve what Object(s) were put into the editor because the method returns a bool and doesn't trigger an Event with a command name! Aside from that, the documentation doesn't give an example. Does anyone know how to use this?

    Thanks in advance;).
     
  2. Retruate

    Retruate

    Joined:
    Jul 5, 2014
    Posts:
    111
    I solved my problem. The object was actually going to the variable in the script my editor script was a type of (the variable the editor script was getting its serialized property from), not the editor script itself. I was able to get an instance of that script using
    Code (CSharp):
    1. GameObject.FindObjectOfType<MyScript>(); //or FindObjectsOfType. Mine only appears once.
    inside of my editor script and call a function inside of it that uses that value.
     
  3. CDF

    CDF

    Joined:
    Sep 14, 2013
    Posts:
    1,311
    if folderProp is an array or List then you can access elements using:

    SerializedProperty myElement = folderProp.GetArrayElementAtIndex(index)
    MyScript obj = myElement.objectReference as MyScript
     
  4. Retruate

    Retruate

    Joined:
    Jul 5, 2014
    Posts:
    111
    Could I use SerializedProperty.arraySize in a foreach loop with that?

    I also assume you mean this. If so, that is super useful! I found a working solution though.

    Thanks;).
     
  5. CDF

    CDF

    Joined:
    Sep 14, 2013
    Posts:
    1,311
    Yes and yes
     
    Retruate likes this.