Hello, im trying to make customclasses that are derived from ScriptableObject work with SerializedProperty
Below, i have made a very minimal and simple example that works without deriving from ScriptableObject.
Human.cs
public class Human : MonoBehaviour
{
public Weapon Weapon;
public int Health;
}
Weapon.cs
[System.Serializable]
public class Weapon
{
public int Damage;
public int Weight;
}
HumanEditor.cs
[CustomEditor(typeof(Human))]
public class HumanEditor : Editor
{
SerializedObject sObj;
void OnEnable()
{
this.sObj = new SerializedObject(target);
Weapon weapon = ((Human)target).Weapon;
if (weapon == null)
weapon = new Weapon();
}
public override void OnInspectorGUI()
{
this.sObj.Update();
SerializedProperty sHealth = sObj.FindProperty("Health");
sHealth.intValue = EditorGUILayout.IntField("Health", sHealth.intValue);
SerializedProperty sWeaponDamage = sObj.FindProperty("Weapon.Damage");
sWeaponDamage.intValue = EditorGUILayout.IntField("Damage", sWeaponDamage.intValue);
SerializedProperty sWeaponWeight = sObj.FindProperty("Weapon.Weight");
sWeaponWeight.intValue = EditorGUILayout.IntField("Weight", sWeaponWeight.intValue);
this.sObj.ApplyModifiedProperties();
}
}
This works. But when i derived weapon from ScriptableObject, and change the OnEnable() function to:
void OnEnable()
{
this.sObj = new SerializedObject(target);
SerializedProperty sWeapon = sObj.FindProperty("Weapon");
if (sWeapon.objectReferenceValue == null)
sWeapon.objectReferenceValue = ScriptableObject.CreateInstance<Weapon>();
}
Then i get an exepction saying its null.
What should i do to make it work with ScriptableObject?
The reason i need this, is because i want to use polymorphism and inheritance with Weapon.