CustomPropertyDrawer and Inheritance / Polymorphism

This is what I have (essentially):

public class Weapon
{ // some public fields and methods
}

public class Axe : Weapon
{ // more public fields and methods
}

public class Inventory : MonoBehavior
{
     Weapon weapon1;
}

I have a custom property drawer for every one of the classes inheriting Weapon. The inspector only seems to want to use a CustomPropertyDrawer for “Weapon”, no matter which Weapon-inherited object I have assigned to the Inventory->Weapon object. Is there an easy way to fix that?

Thanks!

1 Like

I believe you must use a subclass in the declaration because a default inspector isn’t so smart.

You could also make a custom inspector with your own logic (you can dynamically decide which type of object you are expecting to be dragged in).

private Axe _slot;

void OnGUI() {
    _slot = EditorGUILayout.ObjectField("Axe: ", _slot, typeof(Axe));
}

I have the CustomPropertyDrawers setup like so, but it still doesn’t work. Or were you suggesting something else?

[CustomPropertyDrawer (typeof(Weapon))]
public class WeaponDrawer : PropertyDrawer {
// OnGUI override
}

[CustomPropertyDrawer (typeof(Axe))]
public class AxeDrawer : WeaponDrawer{
base.OnGUI(yadda, yadda, yadda);
// OnGUI override for Axe
}

Never used the CustomPropertyDrawer attribute, sorry.

No worries. I got tired of messing with it. I’m just constructing a larger CustomEditor and having each inherited object keep up with it’s own OnGUI function to call during the CustomEditor manipulations. Works amazingly well :slight_smile: I’m intrigued to know what I was doing wrong, but if anyone ever has a similar requirement, my recommendation is to go with the CustomEditor, no matter how much larger of a beast it will be … everything just went so much more smoothly for me in comparison.

Hey yumupdate, can you share code of how you ended up doing this? :slight_smile:

Any updates on this problem? PropertyDrawers and inheritance don’t work well…

You may use useForChildren parameter**:**

useForChildren
If true, the drawer will be used for any children of the specified class unless they define their own drawer.

4 Likes

Hi, I know I’m a little late to the party, but inspired by this answer and my own frustration:

I’ve created a generic and easy to use solution for Polymorphic PropertyDrawers in Unity.

I’ve posted the full details here (ready to Copy & Paste into your own project): CustomPropertyDrawer for polymorphic class - Unity Engine - Unity Discussions

P.S. I am posting here as it’s one of the top search results when looking for “unity polymorphic property drawer” so hopefully it’ll help more people

1 Like