Search Unity

  1. Unity 2018.3 is now released.
    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. We've updated our Terms of Service. Please read our blog post from Unity CTO and Co-Founder Joachim Ante here
    Dismiss Notice
  4. Want to provide direct feedback to the Unity team? Join the Unity Advisory Panel.
    Dismiss Notice
  5. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    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:
    538
    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:
    93
    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:
    538
    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!