- Home /
CustomPropertyDrawer for derived class?
I am trying to display custom editor for derived class (accessed through base class pointer). I've been trying to used PropertyDrawer but that didn't seem to work.
Here's the component:
public class Stat_Unity : MonoBehaviour
{
public Stat stat = new HitpointsStat { name = "abc", hitpoints = 100 };
}
Here are my drawers:
Base class:
[CustomPropertyDrawer(typeof(Stat))]
public class StatEditor : PropertyDrawer
{
public override void OnGUI(Rect position,
SerializedProperty property,
GUIContent label)
{
EditorGUI.BeginProperty (position, label, property);
var nameRect = new Rect(position.x, position.y, 30, position.height);
EditorGUI.PropertyField(nameRect, property.FindPropertyRelative("name"), GUIContent.none);
EditorGUI.EndProperty();
}
}
Derived class:
[CustomPropertyDrawer(typeof(HitpointsStat))]
public class HitpointStatEditor : StatEditor
{
public override void OnGUI(Rect position,
SerializedProperty property,
GUIContent label)
{
base.OnGUI(position, property, label);
EditorGUI.BeginProperty(position, label, property);
var hitpointsRect = new Rect(position.x + 35, position.y, 50, position.height);
EditorGUI.PropertyField(hitpointsRect, property.FindPropertyRelative("hitpoints"), GUIContent.none);
EditorGUI.EndProperty();
}
}
It only displays base class property drawer every time, no matter if it's actually a HitpointStat.
How can I fix this to keep base class pointer access and yet display derived class?
Thanks.
Answer by vexe · Apr 21, 2014 at 09:47 AM
Have you tried the other overload of CustomPropertyDrawer
that takes boolean to use the drawer for children types?
public CustomPropertyDrawer(Type type, bool useForChildren);
thanks for suggestion but this doesn't work when using base class pointer. Looks like the only way to get this to work is to define the property with the derived class to begin with.
Your answer
Follow this Question
Related Questions
Null reference exceptions when using a Custom Editor 0 Answers
Enum Dropdown in JS Using Custom Editor? 2 Answers
Custom Inspector: Accessing a reference to another MonoBehaviour? 1 Answer
What is a GUILayoutOption[] 3 Answers
Custom Inspector & Arrays 0 Answers