Search Unity

Use Custom PropertyDrawer in CustomEditor without PropertyAttribute

Discussion in 'Immediate Mode GUI (IMGUI)' started by Johannski, Jun 4, 2018.

  1. Johannski

    Johannski

    Joined:
    Jan 25, 2014
    Posts:
    826
    Hello there,

    So I'm wondering for quite some time now: Is it possible to use a custom propertydrawer in a custom editor on any property (and even just object references) that don't have the property assigned.

    So for example: I have a customPropertyDrawer for MinMaxAttribute and I would like to do something like
    Code (CSharp):
    1. // Draw a property with a drawer it is not assigned to
    2. EditorGUILayout.PropertyField(property, "Property with other drawer", new PropertyGUILayoutOption(typeof(MinMaxAttribute)));
    3.  
    4. // Draw a object reference with a custom drawer
    5. EditorGUILayout.ObjectField("object reference", customObject,  typeof(Vector2), new PropertyGUILayoutOption(typeof(MinMaxAttribute)));
    Is there anything out there that might fulfill my dreams? Or how are you solving the problem of not writing the same code again for a object reference field that is not directly serialized in your class?
     
    Last edited: Jun 5, 2018
  2. PsyKaw

    PsyKaw

    Joined:
    Aug 16, 2012
    Posts:
    102
    You can instantiate your drawer and call OnGUI() with your property:

    Code (CSharp):
    1. SerializedProperty property = serializedObject.FindProperty("yourPropertyName");
    2. MinMaxDrawer drawer = new MinMaxDrawer();
    3. drawer.attribute = new MinMaxAttribute(0f, 1f);
    4. GUIContent content = new GUIContent(property.displayName);
    5. Rect drawerRect = EditorGUILayout.GetControlRect(true, drawer.GetPropertyHeight(property, content));
    6. drawer.OnGUI(drawerRect, property, content);
    Enjoy!
     
    Johannski likes this.
  3. Johannski

    Johannski

    Joined:
    Jan 25, 2014
    Posts:
    826
    Wow, that's exactly what I was searching for! Very interesting code snippet, I completely missed GetControlRect in the documentation. Thanks a lot for the quick reply!