1+ using System . Collections . Generic ;
2+ using System ;
3+ using UnityEditor ;
4+ using UnityEngine ;
5+
6+ [ Serializable ]
7+ public abstract class Food
8+ {
9+ public string name ;
10+
11+ public float kcal ;
12+ }
13+
14+ [ Serializable ]
15+ public class Apple : Food
16+ {
17+ public Apple ( )
18+ {
19+ name = "Apple" ;
20+ kcal = 100f ;
21+ }
22+ }
23+
24+ [ Serializable ]
25+ public class Peach : Food
26+ {
27+ public Peach ( )
28+ {
29+ name = "Peach" ;
30+ kcal = 100f ;
31+ }
32+ }
33+
34+ [ Serializable ]
35+ public class Grape : Food
36+ {
37+ public Grape ( )
38+ {
39+ name = "Grape" ;
40+ kcal = 100f ;
41+ }
42+ }
43+
44+ public class Example : MonoBehaviour
45+ {
46+
47+ [ SerializeReference ]
48+ public Food food1 = new Apple ( ) ;
49+
50+ [ SerializeReference ]
51+ public Food food2 = new Peach ( ) ;
52+
53+ [ SerializeReference ]
54+ public Food food3 = new Grape ( ) ;
55+
56+ [ SerializeReference , SubclassSelector ]
57+ public Food foodOne = new Apple ( ) ;
58+
59+ [ SerializeReference , SubclassSelector ]
60+ public Food foodTwo = new Peach ( ) ;
61+
62+ [ SerializeReference , SubclassSelector ]
63+ public Food foodThree = new Grape ( ) ;
64+
65+ [ SerializeReference ]
66+ public List < Food > foodsOne = new List < Food >
67+ {
68+ new Apple ( ) ,
69+ new Peach ( ) ,
70+ new Grape ( )
71+ } ;
72+
73+ [ SerializeReference , SubclassSelector ]
74+ public List < Food > foodsTwo = new List < Food >
75+ {
76+ new Apple ( ) ,
77+ new Peach ( ) ,
78+ new Grape ( )
79+ } ;
80+ }
81+
82+ /// These classes are in a folder named "Editor" in the project
83+
84+ [ CustomPropertyDrawer ( typeof ( Peach ) , true ) ]
85+ public class PeachDrawer : PropertyDrawer
86+ {
87+ public override void OnGUI ( Rect position , SerializedProperty property , GUIContent label )
88+ {
89+ position . height = EditorGUIUtility . singleLineHeight ;
90+ EditorGUI . PropertyField ( position , property . FindPropertyRelative ( "name" ) ) ;
91+
92+ position . y += EditorGUIUtility . singleLineHeight + EditorGUIUtility . standardVerticalSpacing ;
93+ EditorGUI . PropertyField ( position , property . FindPropertyRelative ( "kcal" ) ) ;
94+ }
95+
96+ public override float GetPropertyHeight ( SerializedProperty property , GUIContent label )
97+ {
98+ return EditorGUIUtility . singleLineHeight * 2 + EditorGUIUtility . standardVerticalSpacing * 1 ;
99+ }
100+ }
101+
102+ [ CustomPropertyDrawer ( typeof ( Apple ) , true ) ]
103+ public class AppleDrawer : PropertyDrawer
104+ {
105+ public override void OnGUI ( Rect position , SerializedProperty property , GUIContent label )
106+ {
107+ EditorGUI . LabelField ( position , "I'm an apple!" ) ;
108+ }
109+
110+ public override float GetPropertyHeight ( SerializedProperty property , GUIContent label )
111+ {
112+ return EditorGUIUtility . singleLineHeight ;
113+ }
114+ }
0 commit comments