Search Unity

  1. Improved Prefab workflow (includes Nested Prefabs!), 2D isometric Tilemap and more! Get the 2018.3 Beta now.
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. Let us know a bit about your interests, and if you'd like to become more directly involved. Take our survey!
    Dismiss Notice
  4. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice
  5. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

Use Custom PropertyDrawer in CustomEditor without PropertyAttribute

Discussion in 'Extensions & OnGUI' started by Johannski, Jun 4, 2018.

  1. Johannski

    Johannski

    Joined:
    Jan 25, 2014
    Posts:
    519
    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:
    92
    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:
    519
    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!