- Home /
Inspector - editing array of polymorphic objects?
So I have a ScriptableObject with an array of polymorphic objects like this:
[System.Serializable]
public class CMyObject : ScriptableObject
{
public List<CElementBase> _Elements = new List<CElementBase>();
}
[System.Serializable]
public class CElementBase
{
public string _Name;
}
[System.Serializable]
public class CElementInt : CElementBase
{
public int _SomeInt;
}
[System.Serializable]
public class CElementString : CElementBase
{
public string _SomeString;
}
Is there a good way to use the inspector to add and edit derived-class element to the array?
I was able to add the support for adding derived classes using CustomEditor for MyObject and
public override void OnInspectorGUI()
{
DrawDefaultInspector ();
CMyObject myTarget = (CMyObject) target;
if(GUILayout.Button("Add Int"))
{
myTarget._Elements.Add ( new CElementInt() );
}
if(GUILayout.Button("Add String"))
{
myTarget._Elements.Add ( new CElementString() );
}
But even so, the elements that show up in the array only allow me to edit the base class properties (_Name), not the derived class ones (_SomeInt or _SomeString).
Is there a way to have Unity let me edit the actual derived class, or do I need to manually create edit fields for each property based on the type? Please advise!
Answer by koobazaur · Jan 04, 2014 at 12:21 AM
So I just found out every time I recompile my scripts it somehow reverts the derived class back to its base class (thus losing the _SomeInt and _SomeString params). Blast - what am I doing wrong?
EDIT: found my answer: http://forum.unity3d.com/threads/155352-Serialization-Best-Practices-Megapost
Answer by $$anonymous$$ · Jan 03 at 07:31 PM
It's possible natively since 2019.3 release via [SerializeReference] attribute https://docs.unity3d.com/ScriptReference/SerializeReference.html