- Home /
PropertyDrawer: Enum to select extended class
I am experimenting with unitys editor, to see what I can do and learn it a bit. At the moment I am stuck with one of my experiments.
I have a class called UIElement and have other classes extend of it (eg: UIButton and UILabel). I wish for the different extension to be selectable/changeable in the editor so I have been working on a PropertyDrawer for the class and created enums to help. However im stuck on switching the types on based on the selected enum (and keeping it switched, even on scene save and load).
So, in other words... I wish to be able to switch the classes (that are extended of UIElement) using a enum and PropertyDrawers. Is this even possible and if so, how can I achive it?
Here is a shot of what I currently have to help give more understanding:
Here is my classes:
public class UIElement {
public UIType uiType { get { return getUIType(); } }
public string name;
public Rect position;
public virtual void OnGUI () {}
public virtual void OnInspector (Rect position, SerializedProperty property) {}
public virtual UIType getUIType() { return UIType.label; }
}
[Serializable]
public class UIButton : UIElement {
public Texture2D image;
public override void OnGUI () {
}
public override void OnInspector(Rect position, SerializedProperty property) {
EditorGUI.PropertyField(position, property.FindPropertyRelative("image"));
}
public override UIType getUIType() { return UIType.button; }
}
[Serializable]
public class UILabel : UIElement {
public string text;
public override void OnGUI () {
}
public override void OnInspector(Rect position, SerializedProperty property) {
EditorGUI.PropertyField(position, property.FindPropertyRelative("text"));
}
public override UIType getUIType() { return UIType.label; }
}
And here is my PropertyDrawer at the moment:
[CustomPropertyDrawer(typeof(UIElement))]
public class UIElementDrawer : PropertyDrawer {
public UIType tpe;
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) {
//Debug.Log(property.FindPropertyRelative("uiType").intValue);
label = EditorGUI.BeginProperty(position, label, property);
position.height = 16;
tpe = (UIType) EditorGUI.EnumPopup(position,label,tpe);
position.y += 18;
EditorGUI.PropertyField(position, property.FindPropertyRelative("name"));
position.y += 18;
EditorGUI.PropertyField(position, property.FindPropertyRelative("position"));
position.y += 18;
//Im stuck here, how do i change stuff?
/*switch(label) {
}*/
EditorGUI.EndProperty();
}
public override float GetPropertyHeight (SerializedProperty property, GUIContent label) {
return 18F*4F;
}
}
Thank you in advance, and I'm sorry im not very good at explaining things :\\
I can't try right, but maybe you can use generic ? Like :
[CustomPropertyDrawer(typeof(T))]
public class UIElementDrawer <T>: PropertyDrawer where T : UIElement { ...
Sadly that does not work, and it would still leave me the issue of swapping types when the enum is changed :(