r/Unity3D•
booljayj

Serializing nested generic types in concrete classes

Question

I'm having some serialization issues involving nested generic types. I am fully aware that Unity will not serialize generic types, and that they must be made into concrete classes. However, I am finding that nested generics still don't serialize when made into concrete classes.

For example, I have a generic type that contains another generic type:

[Serializable] public class Placement<T> {
    [SerializeField] Vector3 _position;
    [SerializeField] WeightedList<T> _list;
}

The definition for WeightedList<T> is also marked appropriately

[Serializable] public class WeightedList<T> {
    [Serializable] class WeightedEntry {
        public int weight;
        public T obj;
    }
    [SerializeField] WeightedEntry[] _entries;
}

Now, when I use the Placement class, I make it into a concrete class.

[Serializable] public class Round {
    [Serializable] public class Object1Placement : Placement<CustomComponent> {}
    [Serializable] public class Object2Placement : Placement<CustomComponent> {}

    [SerializeField] Object1Placement[] _list1;
    [SerializeField] Object2Placement[] _list2;
}

Now, when I look at my two lists in the last code section, I can see that the Vector3 position field is properly serialized, but the WeightedList field is not there. When I make Placement<T> into a concrete class, it should also make the nested WeightedList<T> into a concrete class, which means it should be serializable. Any clue about why Unity isn't picking this up?

For further information, adding a List<T> _otherList field to the Placement<T> class does show up in the inspector, so Unity is obviously able to tell what the type should be in that case, but not when it comes to a custom class.

Posted Feb 21, 2016, 8:47 PM UTC

35
Loading comments…