0
\$\begingroup\$

Say you have the following code:

[Serializable]
public abstract class AbstractBase { }

[Serializable]
public abstract class GenericSubclass<T> : AbstractBase
{
    public T Data;
}

[Serializable]
public class OtherClass
{
    // contains mixture of value and reference type fields
}

And say you need the following instantiations of GenricSubclass:

[Serializable]
public class ConcreteSubclass : GenericSubclass<OtherClass> { }

[Serializable]
public class ContainerSubclass : GenericSubclass<List<AbstractBase>> { }

Is there any way for both ConcreteSubclass and ContainerSubclass to be serializable at the same time? As far as I can tell, you can make ContainerSubclass at least serializable (if not fully editable in the inspector) by adding a [SerializeReference] attribute to Data, but that seems to break the serialization of ConcreteSubclass, and otherwise seems kind of fragile (ie, two MonoBehaviours can't share an object serialized by reference).

As for motivation, I'm using this structure to implement a virtual filesystem. Files have certain shared members regardless of what kind of data they hold, but any actual file must have a type in order to be associated with data of that type. ConcreteSubclass is a stand-in for files that hold reference types as their data, while ContainerSubclass is a stripped down version of how I'm handling directories. I'm using Unity 2019.4.

\$\endgroup\$
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.