I’m trying to serializa a custom abstract class but I can’t reach a point picking which derived class it should be.
I saw that OdinInspector can do this if my field is inside a SerializedMonoBehaviour instead of MonoBehaviour. However I don’t want this dependency.
Anyone figures out how to reach this kind of serialization?
I’ve the inspector look and functionality ready, I only miss how to (any way, this is an example of my missing point)
property.objectReferenceValue = myCustomAbstractClass
public abstract class Condition
public string Name;
public class IntCondition : Condition
[SerializeField] int _comparisonTerm1 = 0;
[SerializeField] int _comparisonTerm2 = 0;
public class BoolCondition : Condition
[SerializeField] bool _comparisonTerm = false;
public class ExampleScript : MonoBehaviour
[SerializeField] Condition _condition = null;
Your question is a bit confusing. I guess by
No-MonoBehaviour / No-ScriptableObject
you mean that you still want the class to be serialized inside a MonoBehaviour but the abstract class itself is not a MonoBehaviour / ScriptableObject.
Originally Unity did not support any sort of polymorphism for custom serializable classes. This was the case for years. Unity now introduced the SerializeReference attribute. This allows to serialize plain C# classes and support polymorphism. However even Unity does support serialzing such class constructs, Unity does not provide any built-in way to create those classes. You have to provide your own custom editor / property drawer any implement whatever you need.
One of the issues that Unity would have is: what classes it should offer for you? What if those classes do not have a parameterless constructor? What if the type is a generic type? Solutions like the OdinInspector applies several restrictions and applies some assumptions how you may use such references. Though Unity now supports “object” variables as well which could contain literally any C# object that is serializable. So how would an inspector look like? How would you choose which object should be created?
Of course my last question can usually easily be answered in a specific case, as your concrete example. However Unity does not know your intentions. There are many editor UI implementations out there which provide different level of automatic support for derived classes. Have a look over here. Maybe in the future Unity implements something similar as well. However this would be a neverending story and would produce more and more grief among users as there’s always that one specific usecase that SerializeReference can handle but the UI doesn’t.