- Home /
Problem is not reproducible or outdated
How to insert an element of specific type to a list as serializedProperty?
I' writing on a custom editor for a class OtherClass
containing a List<MyBaseClass>
.
I'm deriving various other classes e.g. MyIntClass
, MyListClass
, etc from MyBaseClass
.
Later I allow to add all those classes to the list in order to get them serialized in XML like
[XmlArrayItem(Type = typeof(MyIntClass), ElementName = "Int")]
[XmlArrayItem(Type = typeof(MyListClass), ElementName = "List")]
public List<MyBaseClass> Items = new List<MyBaseClass>();
Adding elements via script just works like e.g.
Items.Add(new MyIntClass(5));
Items.Add(new MyListClass(someList));
But now I want to add items from the inspector, so I'm writing a custom editor script. The goal is that you can choose what type shall be added to the list, set some values and hit ADD.
But I'm stuck on the point where elements with different types shall be added.
I know usually you can do something like
SerializedProperty _list = serializedObject.FindProperty("Items");
_list.InsertArrayElementAtIndex(_list.arraySize);
But this will allways add an element of type MyBaseClass.
(How) Can I make the added element have a specific type like e.g. MyIntClass
?
Answer by Bunny83 · May 03, 2018 at 09:25 AM
In short: You can't with normal serializable classes as Unity's serialization system does not support polymorphism for custom serializable classes.
Make sure you read the script serialization documentation page carefully.
Serializable structs and classes are actually serialized "inline" in either a MonoBehaviour or a ScriptableObject. Only those two base classes support inheritance / polymorphism. If you haven't set the asset serialization mode to "force text" yet you may try that and have a look at how the serialized data actually looks like. If you're not familiar with the YAML format, have a look at Unity's documentation and at the example file. All serialized fields of a component / ScriptableObject are serialized / deserialized based on the field type. The only exception are serialized references which only work for UnityEngine.Object derived classes (and MonoBehaviour and ScriptableObject are the only two base classes for your own classes).
Follow this Question
Related Questions
Unable to serialize my list in a Unity Custom Editor script. 1 Answer
A node in a childnode? 1 Answer
Finding property with serializedObject on script with a generic 0 Answers
Using Generic List with serializedProperty Inspector 3 Answers
Why would pressing the play button delete or recreate a list elements? 1 Answer